17370845950

c#之添加window服务(定时任务)

本文详细介绍了如何使用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服务上的定时任务已成功生效。

参考网址:https://www./link/f17a5d67253e3c9c77404e31c6f25c55