C#添加Windows服务实现定时任务
本文详细介绍了如何使用Windows服务创建定时任务的步骤。1.首先,创建一个新的项目。在Windows桌面中,选择Windows服务选项。2.接着,右键点击项目,选择添加安装程序。3.在安装程序上右键点击serviceInstaller1,修改serviceName和Description。4.然后,在serviceProcessInstaller上右键点击,选择并修改Account为LocalSystem。5.在Service1中添加以下代码:publicpartialclassService1
本文详细介绍了如何使用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:\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的位置如图所示:

由此可见,Windows服务上的定时任务已成功生效。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















