博客
关于我
C# 建一个Windows 服务 定时发邮件
阅读量:734 次
发布时间:2019-03-21

本文共 1793 字,大约阅读时间需要 5 分钟。

在Windows环境中创建并管理Windows服务

1. 使用Visual Studio创建Windows服务

首先,在Visual Studio中创建一个基于.NET Framework的Windows服务项目。打开Visual Studio后,按照以下步骤操作:

  • 创建项目:选择“文件” > “新建项目”,然后选择“Windows服务”模板,填写项目名称和保存目录。
  • 配置项目:在“项目属性”中调整服务名称、存储目录等设置。

2. 添加安装程序

完成项目创建后,可以通过以下步骤添加安装程序:

  • 右键点击项目文件,选择“添加” > “安装程序资源”,然后启用默认的InstallUtil.exe配置。
  • 这一步将确保服务能够在系统上正确安装。

3. 调整服务属性

安装程序添加后,右键点击服务控件(如serviceInstaller1),选择“属性”进入设置界面。

  • 设置服务属性:修改service name、service description以及display name,确保服务在管理界面中能够清晰显示。

4. 编写服务代码

确保项目中包含以下必要的编程元素:

  • 服务启动逻辑:在OnStart方法中添加启动代码,如日志记录、定时任务配置等。
  • 服务停止逻辑:在OnStop方法中添加停止代码,如清理资源、关闭连接池等。
  • 定时任务:使用System.Timers.Timer实现定时任务,确保服务在特定时间执行必要操作。
using System;using System.Configuration;using System.ServiceProcess;using System_Timer;public partial class Service1 : ServiceBase{    public Service1()    {        InitializeComponent();        var timer = new Timer();        timer.Interval = 1000; // 每秒执行一次        timer.Enabled = true;    }    protected override void OnStart()    {        WriteLog("【服务已启动】");    }    protected override void OnStop()    {        WriteLog("【服务已停止】");    }    private void WriteLog(string message)    {        var logPath = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt";        var file = new FileInfo(logPath);        if (!file.Exists)        {            File.Create(logPath);        }        var fs = File.AppendAllLines(logPath, Encoding.UTF8);        fs.WriteLine(DateTime.Now + " - [服务日志] " + message);        fs.Close();    }}

5. 安装并运行服务

通过命令行工具安装和管理服务:

  • 安装服务:使用以下命令安装服务(确保路径正确):
    %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe path\YourService.exe
  • 启动服务
    net start YourService
  • 停止服务
    net stop YourService
  • 删除服务
    sc delete YourService

6. 服务管理

使用命令行管理服务:

  • 查看服务状态:使用net status YourService命令查看服务状态。
  • 服务日志管理:通过服务控制台或日志文件查看服务运行日志。

通过以上步骤,您可以在Windows环境中成功创建、配置并管理自定义的Windows服务。

转载地址:http://qudgz.baihongyu.com/

你可能感兴趣的文章
Nginx配置TCP代理指南
查看>>
Nginx配置代理解决本地html进行ajax请求接口跨域问题
查看>>
Nginx配置参数中文说明
查看>>
Nginx配置好ssl,但$_SERVER[‘HTTPS‘]取不到值
查看>>
Nginx配置实例-负载均衡实例:平均访问多台服务器
查看>>
NIFI大数据进阶_连接与关系_设置数据流负载均衡_设置背压_设置展现弯曲_介绍以及实际操作---大数据之Nifi工作笔记0027
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
nio 中channel和buffer的基本使用
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>