Window timer task scheduling service implementation (b) component based Quartz.Net

Preface :

   In the previous chapter , we achieved a timing task scheduling by using the console, has a general understanding of how tasks are based Quartz.Net assembly, comprising at least three parts: job (job), Trigger (trigger), Scheduler (scheduler) . Wherein the business logic is a need for specific job performed in a timed task, and trigger when the job by a predetermined specified rules according to which execution of the last job and trigger are registered in the scheduler, using the scheduler (Scheduler) responsible coordination with the job and trigger the run.

  Do you need to experience the software has the function automatically perform tasks at work, but do not want to directly launch the software manually perform the task? 

                         

  This time, we can consider use window service, based on the timing of polling Quartz.Net component database synchronization, regular mail notifications, time data processing and other functions.

Start :

First create a windows service project

Creating a good project, Service1.cs file, click on the "Click here to switch to code view" switch to code

This time we can note two methods: the OnStart   (service starts) and  OnStop (service stop)

        /// <summary>
        /// 服务启动
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
        }
        /// <summary>
        /// 服务停止
        /// </summary>
        protected override void OnStop()
        {
        }

一、创建一个scheduler的引用

            ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler sched = await schedFact.GetScheduler();

二、启动 scheduler:

            await sched.Start();

三、实现IJob:

SyncJob.cs 实现IJob,在Execute方法里编写要处理的业务逻辑,系统就会按照Quartz的配置,定时处理

    [Invoke(Name = "SyncJob", Remark = "Quartz服务", Group = "Quartz服务管理", Begin = "2018-05-01 12:00:00", Interval = 5)]
    public class SyncJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                //每次执行 获取当前时间 输出当前时间
                //可以在这里编写每次定时执行需要的方法
                LogHelper.SaveLog("输出日志", "在当前时间:" + DateTime.Now + "--上一次执行时间:" + DateTime.Now.AddSeconds(-5));
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
            }

            return null;
        }
    }

四、创建trigger:(建立一个某个时间点的触发器,并且每5秒执行一次)

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")  //触发器 组
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
                .Build();

五、触发器执行任务:

            await sched.ScheduleJob(job, trigger);

将几个步骤整合后代码如下:

        /// <summary>
        /// 服务启动
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            Run().GetAwaiter().GetResult();
            LogHelper.SaveLog("服务", "开始");
        }
        /// <summary>
        /// 服务停止
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                if (scheduler != null)
                {
                    scheduler.Shutdown();
                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
            }
            LogHelper.SaveLog("服务", "结束");
        }

        IScheduler scheduler;
        private async Task Run()
        {
            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                scheduler = await factory.GetScheduler();

                await scheduler.Start();
                Jobs.Jobs.Config(scheduler);
            }
            catch (SchedulerException ex)
            {
                LogHelper.SaveLog(ex);
            }

        }

安装

以管理员的身份打开cmd

 

运行

间隔5秒执行一次后的效果:

通过日志的方式输出数据,查看效果

附加

 一、删除服务

以管理员的身份打开cmd

 

二、调试window服务

1)安装并运行服务

 

2)附加进程

3)在代码中加入断点进行调试

总结

1.当我们在需要用到定时执行任务的时候,可以考虑使用通过window服务加上quartz组件结合的方式,实现对任务的定时执行,这也是在很多场景中可以实现的方法,比如:定时轮询数据库同步,定时邮件通知,定时处理数据等

2.通过管理工具显示当前执行的任务和执行情况,也利用调试工具调试Window服务中遇到的问题。

3.quartz还有更多的用法,可以参考资料:Quartz.Net官方文档   和  Quartz.Net开源地址

Guess you like

Origin www.cnblogs.com/i3yuan/p/11373527.html