C# 通过 Quartz .NET 实现Timer Job并将其注册成为Windows Service

之前的一篇文章讲述了如何通过 Quartz .NET 实现 Timer Job (http://www.cnblogs.com/mingmingruyuedlut/p/8037263.html)

在此基础上如何将实现的Timer Job注册成为Windows Service,请看如下步骤:

1):在VS中创建Windows Service的工程

2):继承 IJob 接口实现对文本文件的写值

using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTimerWinSerApp
{
    public class EricSimpleJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            string filepath = @"C:\timertest.txt";

            if (!File.Exists(filepath))
            {
                using (FileStream fs = File.Create(filepath)) { }
            }

            using (StreamWriter sw = new StreamWriter(filepath, true))
            {
                sw.WriteLine(DateTime.Now.ToLongTimeString());
            }

            return Task.CompletedTask;
        }
    }
}

3):完成 IScheduler, IJobDetail 和 ITrigger 的相关配置

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTimerWinSerApp
{
    public class JobScheduler
    {
        public async void Start()
        {
            var props = new NameValueCollection
            {
                { "quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory schedFact = new StdSchedulerFactory(props);

            IScheduler sched = await schedFact.GetScheduler();
            await sched.Start();

            IJobDetail job = JobBuilder.Create<EricSimpleJob>()
                .WithIdentity("EricJob", "EricGroup")
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("EricTrigger", "EricGroup")
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
                .Build();

            await sched.ScheduleJob(job, trigger);
        }

        public async void Stop()
        {
            IScheduler sched = await StdSchedulerFactory.GetDefaultScheduler();
            await sched.Shutdown();
        }
    }
}

4):完成工程中Service1的处理

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTimerWinSerApp
{
    public partial class Service1 : ServiceBase
    {
        JobScheduler scheduler;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            scheduler = new JobScheduler();
            scheduler.Start();
        }

        protected override void OnStop()
        {
            if (scheduler != null)
                scheduler.Stop();
        }
    }
}

5):完成Program.cs中Main函数的处理

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTimerWinSerApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

6):完成上述代码之后,build出来的exe执行文件,放到指定的目录中,然后用 .Net Framework 中的 InstallUtil.exe 完成对service的注册 (例如InstallUtil.exe为目录为:C:\Windows\Microsoft.NET\Framework64\v4.0.30319),注:要以管理员的身份运行cmd

如果想要卸载对应的服务,那么对应的命令行为:InstallUtil.exe  /u  C:\CustomerWinService\....exe

7): 到Service管理界面找到刚刚安装上的Service,然后右键启动,之后就可以到对应的txt文件中看到 Timer Job 所写入的内容

更多相关内容请参考如下链接:

http://www.codingdefined.com/2016/08/schedule-tasks-as-windows-service-using.html

http://www.c-sharpcorner.com/UploadFile/8f2b4a/how-to-installuninstall-net-windows-service-C-Sharp/

猜你喜欢

转载自www.cnblogs.com/mingmingruyuedlut/p/9033159.html
今日推荐