c#之添加window服务(定时任务)
本文讲述使用window服务创建定时任务
1.如图,新建项目,windows桌面->windows服务
2.如图,右键,添加安装程序
3.在下图安装程序 serviceinstaller1 上右键,修改servicename和description
4.如图,在 serviceprocessinstaller 上右键,修改 account 为 localsystem
5.在service1中 添加代码
public partial class service1 : servicebase { //记录到event log中,地址是 c:\windows\system32\winevt\logs (双击查看即可,文件名为mynewlog) private static eventlog eventlog1; private int eventid = 1; public service1() { initializecomponent(); eventlog1 = new system.diagnostics.eventlog(); if (!system.diagnostics.eventlog.sourceexists("mysource")) { system.diagnostics.eventlog.createeventsource( "mysource", "mynewlog"); } eventlog1.source = "mysource"; eventlog1.log = "mynewlog"; } /// <summary> /// 启动服务 /// </summary> /// <param name="args"></param> protected override void onstart(string[] args) { eventlog1.writeentry("in onstart."); log("in onstart."); // set up a timer that triggers every minute. 设置定时器 timer timer = new timer(); timer.interval = 60000; // 60 seconds 60秒执行一次 timer.elapsed += new elapsedeventhandler(this.ontimer); timer.start(); } /// <summary> /// 停止服务 /// </summary> protected override void onstop() { eventlog1.writeentry("in onstop."); log("in onstop."); } /// <summary> /// 继续服务 /// </summary> protected override void oncontinue() { eventlog1.writeentry("in oncontinue."); log("in oncontinue."); } /// <summary> /// 定时器中定时执行的任务 /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public void ontimer(object sender, elapsedeventargs args) { // todo: insert monitoring activities here. eventlog1.writeentry("monitoring the system", eventlogentrytype.information, eventid++); log("the timer"); } /// <summary> /// 记录到指定路径:d:\log.txt /// </summary> /// <param name="message"></param> private static void log(string message) { using (filestream stream = new filestream("d:\\log.txt", filemode.append)) using(streamwriter writer=new streamwriter(stream)) { writer.writeline($"{datetime.now}:{message}"); } } }
结构如图:
6.右键生成解决方案
7.打开项目,复制bin目录到c盘下新建的 windowservicetest 文件夹的 windowservice_hello文件夹下,另外复制 c:\windows\microsoft.net\framework\v4.0.30319 下的 installutil.exe 到 windowservicetest 文件夹下;如图
8.安装服务
打开cmd (以管理员身份),并且进入windowservicetest 文件夹下
安装服务:
installutil.exe c:\windowservicetest\windowservice_hello\bin\debug\windowservice_helloworld.exe
效果图:
9.打开服务管理器,启动myservice服务,并且等待几分钟,然后卸载服务
卸载服务:
installutil.exe -u c:\windowservicetest\windowservice_hello\bin\debug\windowservice_helloworld.exe
10.检验是否有效果
在d盘发现log.txt文件,打开如下
event log 所在如图
可见,window服务上的定时任务已生效
参考网址
https://docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer
上一篇: JAVA基础之正则表达式