本文详细介绍了如何使用windows服务创建定时任务的步骤。
1.首先,创建一个新的项目。在Windows桌面中,选择Windows服务选项。

2.接着,右键点击项目,选择添加安装程序。

3.在安装程序上右键点击serviceInstaller1,修改serviceName和Description。

4.然后,在serviceProcessInstaller上右键点击,选择并修改Account为LocalSystem。

5.在Service1中添加以下代码:
public partial class Service1 : ServiceBase{ 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"; } protected override void OnStart(string[] args) { eventLog1.WriteEntry("In OnStart."); log("In OnStart."); Timer timer = new Timer(); timer.Interval = 60000; timer.Elapsed += new ElapsedEventHandler(this.OnTimer); timer.Start(); } protected override void OnStop() { eventLog1.WriteEntry("In OnStop."); log("In OnStop."); } protected override void OnContinue() { eventLog1.WriteEntry("In OnContinue."); log("In OnContinue."); } public void OnTimer(object sender, ElapsedEventArgs args) { eventLog1.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++); log("the timer"); } 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:WindowsMicrosoft.NETFramework4.0.30319目录中复制InstallUtil.exe到windowServiceTest文件夹下。


JoinMC智能客服
JoinMC智能客服,帮您熬夜加班,7X24小时全天候智能回复用户消息,自动维护媒体主页,全平台渠道集成管理,电商物流平台一键绑定,让您出海轻松无忧!
23 查看详情
8.安装服务:以管理员身份打开cmd,进入windowServiceTest文件夹,执行以下命令:
InstallUtil.exe C:windowServiceTestwindowService_HelloinDebugWindowService_HelloWorld.exe
安装效果图:

服务管理器中的效果图:

9.打开服务管理器,启动MyService服务,等待几分钟后,卸载服务。卸载命令如下:
InstallUtil.exe -u C:windowServiceTestwindowService_HelloinDebugWindowService_HelloWorld.exe
卸载效果图:

10.检查效果:在D盘中找到log.txt文件,打开内容如下:

Event Log的位置如图所示:

由此可见,Windows服务上的定时任务已成功生效。
参考网址:https://www.php.cn/link/f17a5d67253e3c9c77404e31c6f25c55
以上就是c#之添加window服务(定时任务)的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/353327.html
微信扫一扫
支付宝扫一扫