版权声明:add oil https://blog.csdn.net/dekesun/article/details/88225791
如何创建基于Windows系统运行的服务程序
说明:LZ在做项目的时候,发现有的功能需要使用定时服务程序来执行。在服务程序中写一些业务处理逻辑,再设置定时启动间隔时间,抱着学习的态度,下面记录了实现过程,如有更好的建议,可@LZ,谢谢。
- 开发工具:VS2015
- 运行环境Win10
- 打开VS 文件–>新建–>项目–>Windows服务
- 双击Service1.cs 添加安装程序
- 安装程序添加成功
- 设置serviceInstaller1服务名称为程序名称
- 设置serviceProcessInstaller1
- 将原来的service1.cs中的代码做更改,实现每10s向指定文件中写入一行数据
using System;
using System.ServiceProcess;
using System.IO;
namespace WindowsService3
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer mainTimer;
int count = 0;
string writeFilePath = @"C:\Users\Administrator\Desktop\mpdvVerification\444\Test.log";
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
mainTimer = new System.Timers.Timer(10000);
mainTimer.Elapsed += new System.Timers.ElapsedEventHandler(mainTimer_Elapsed);
mainTimer.Enabled = true;
}
protected override void OnStop()
{
mainTimer.Enabled = false;
}
private void mainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Write();
}
private void Write()
{
using (StreamWriter sw = new StreamWriter(writeFilePath, true))
{
sw.WriteLine(DateTime.Now.ToString()+":执行定时程序第‘" + count.ToString() + "’次。");
}
}
}
}
- 创建启动服务文件Install.bat,并向文件中添加命令
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsService3.exe
Net Start WindowsService3
sc config WindowsService3 start= auto
- 创建卸载服务文件UnInstall.bat,并向文件中添加命令
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsService3.exe
- 右键项目生成,在程序的debug目录下将启动程序复制出来,放到另外一个文件中。与启动和卸载文件放在一起。
- 以管理员权限运行cmd,运行Install.bat,运行成功后,可以看到任务管理器中有一个我们创建的服务在执行。
- 查看记录的log文件,可以看到每一定时间,就会运行一次。
- 以管理员权限运行cmd,运行UnInstall.bat,卸载服务程序。卸载成功以后任务管理器中的服务也同时自动终止服务。
至此如果没问题,表示你的程序创建基本完成,如果有问题,可以骚扰LZ,LZ是个乐于助人的菜鸟。