1.创建服务:选择Windows服务创建项目
2.添加安装程序,生成对应的服务
3.属性设置
4.编写定时服务需要执行的业务
using Common.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WindowsServiceTest
{
public partial class Service1 : ServiceBase
{
private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Service1()
{
InitializeComponent();
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
log.Info("===============服务启动==============");
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
timer.Interval = 5000; //设置多久执行一次
timer.Enabled = true;
}
/// <summary>
/// 执行的方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
int count = 0;
for (int i = 0; i < 5000; i++)
{
count++;
}
}
/// <summary>
/// 停止服务
/// </summary>
protected override void OnStop()
{
log.Info("===============服务停止==============");
}
}
}
5.重新生成编译代码
(1)复制文件到项目的DBUG下
(2)服务安装:%~dp0InstallUtil.exe %~dp0WindowsServiceTest.exe
服务卸载:%~dp0InstallUtil /u %~dp0WindowsServiceTest.exe
写入txt中,修改后缀名为bat使用管理员身份运行
CMD输入:services.msc打开服务结果如下: