zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    30天敏捷生活(4): 撰写个人使命宣言
    [智力考题]比尔盖茨只有3分的考题
    推荐下载:MSN机器人源代码(C#),含自动IP地址查询、简单自动问答等(添加详细使用)
    [代码]包括所有特性的目录选择对话框
    开源数据库系统之SQLite3.2.0、FireBird2.0 Alpha1等
    [建议]添加模板功能
    到底SQLite有多强?在我的2台机器上的压力测试
    OMEA Pro,刚刚荣获15届Jolt大奖,综合RSS阅读,邮件、任务等管理的IIM(智能信息管理)
    关于DotNetNuke(DNN)的语言问题
    写你自己的反编译/混淆器
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/10859129.html
Copyright © 2011-2022 走看看