C#添加Window服务实现定时任务

通过C#来实现在Window服务中添加定时任务进程而达到服务接口定时调用的功能。

1.如图,新建项目,windows桌面->windows服务

 

2.如图,右键,添加安装程序

3.在下图安装程序 serviceInstaller1 上右键,修改serviceName和Description

 4.如图,在 serviceProcessInstaller 上右键,修改 Account 为 LocalSystem 

5.在Service1中 添加代码

public partial class Service1 : ServiceBase
    {
        //记录到event log中,地址是 C:\Windows\System32\winevt\Logs (双击查看即可,文件名为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}");
            }
        }

    }

 结构如图:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦想天涯~路在脚下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值