博客
关于我
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/

你可能感兴趣的文章
Python os.system执行多条语句,os.system的返回值以及与os.popen的区别
查看>>
Python os和sys模块
查看>>
python os文件/目录
查看>>
Python Package 之 Faker(随机姓名、电话)
查看>>
python运算符优先级
查看>>
Python Panda TIME 系列重新采样
查看>>
python pandas TimeStamps到夏令时的本地时间字符串
查看>>
Python pandas 数据清洗与数据绘图实战
查看>>
Python Pandas 用顶行替换标题
查看>>
Python pandas 通过 dt 访问器有效地将日期时间转换为时间戳
查看>>
Python Pandas-从DataFrame按类别绘制多个条形图
查看>>
Python Pandas:每月或每周拆分 TimeSerie
查看>>
python pandas中融化的对面
查看>>
python pandas从时间序列中提取唯一日期
查看>>
Python Pypi 修改 国内源(以豆瓣源为例)
查看>>
Python PyQt5 将不再显示此消息复选框添加到 QMessageBox
查看>>
Python PyQt5:如何使用 PyQt5 显示错误消息
查看>>
Python PYSFTP-以字符串/文本形式传递私钥,而不是传递文件路径
查看>>
Python pytest 面试题!
查看>>
Python pytz 时区函数返回一个相差 9 分钟的时区
查看>>