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

你可能感兴趣的文章
PostGreSql学习笔记001---PostgreSQL10.4安装(Windows)_支持PostGreGis_PostJDBC
查看>>
PostGreSql学习笔记002---Navicat Premium中管理PostGreSql 错误:字段rolcatupdate 不存在
查看>>
PostgreSQL学习笔记:PostgreSQL vs MySQL
查看>>
PostgreSQL实现shape数据转geojson数据(地图工具篇.18)
查看>>
PostgreSQL导入shape数据(地图工具篇.10)
查看>>
PostGreSql工作笔记003---在Navicat中创建数据库时报错rolcatupdate不存在_具体原因看其他博文_这里使用pgAdmin4创建管理postgre
查看>>
PostGreSql工作笔记004---PostGreSql修改密码_windows和linux下修改
查看>>
Postgresql常用命令行操作_以及Navicat操作PostGis时的问题_自动截取长度_WKB structure does not match exp---PostgreSQL工作笔记005
查看>>
PostgreSQL忘记密码
查看>>
PostgreSQL数据库pg_dump命令行不输入密码的方法
查看>>
PostgreSQL新手入门
查看>>
postgresql树状结构查询示例
查看>>
PostgreSQL流复制参数max_wal_senders详解
查看>>
postgresql流复制配置
查看>>
PostgreSQL清空表并保留表结构、清空数据库还原数据库为新建时的状态的方法
查看>>
PostgreSQL的 initdb 源代码分析之九
查看>>
PostgreSQL的安装与使用指南
查看>>
postgresql编译安装及配置
查看>>
Postgresql运维常用命令_登录_权限设置_创建用户_创建数据库_创建postgis数据库_远程连接---Postgresql工作笔记009
查看>>
PostgreSQL远程连接配置
查看>>