• 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:WindowsSystem32winevtLogs (双击查看即可,文件名为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:WindowsMicrosoft.NETFrameworkv4.0.30319 下的 InstallUtil.exe 到 windowServiceTest 文件夹下;如图

     

    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 所在如图

    可见,window服务上的定时任务已生效

    参考网址

    https://docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

  • 相关阅读:
    VS2017常用快捷键
    浅谈JS之setTimeout与setInterval
    你真的了解foreach吗?
    IEnumerable和IEnumerator详解
    Cesium坐标系及坐标转换详解
    NPM常用指令
    ASP.NET Web API 2系列(三):查看WebAPI接口的详细说明及测试接口
    【nginx】安装nginx
    【redis】本地连接服务器的redis教程
    Mysql5.7及以上版本 ONLY_FULL_GROUP_BY报错的解决方法
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/10859129.html
Copyright © 2020-2023  润新知