Job scheduling framework Quartz.NET- off now -02- monitor tasks - simple book

Original: job scheduling framework Quartz.NET- off now -02- monitor tasks - simple book

 

Foreword

Task scheduling system is not perfect, if the task fails it will appear. If you need to handle the logic after the mission failed, I hope this note may provide some help for you.
Quartz.NET task monitoring system has been used in my project has been on-line, pro-test no pit.

Quartz.Listener

To create a listener, simply create an object to achieve ITriggerListener or IJobListener interface. Then run when registering listeners to the dispatcher, and must be (more precisely, they themselves must be uniquely identified by its Name property.) Assign a name

The key interfaces and classes

  • IJobListener - job-related events include: notification is about to perform a job, and the job completion notification when execution.
  • ITriggerListener - associated with the trigger events include: the trigger to fire, triggering false triggering and trigger complete (the trigger to fire the job is completed).
  • ListenerManager - ListenerManager listener with the dispatcher registered together, and comes with a Matcher, used to describe an event listener want to receive jobs / triggers.

Sample Application

using Quartz;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using System;
using System.Collections.Specialized;
using System.Threading;
using System.Threading.Tasks;

namespace QuarzLis
{
    class Program
    {
        static void Main(string[] args)
        {
            StartUpJobs.StartUp().GetAwaiter().GetResult();
            Console.ReadKey();
        }

        public static class StartUpJobs
        {
            public static async Task StartUp()
            {
                try
                {
                    //第一步:从工厂中获取Scheduler实例
                    NameValueCollection props = new NameValueCollection();
                    StdSchedulerFactory factory = new StdSchedulerFactory(props);
                    IScheduler scheduler = await factory.GetScheduler();
                    //第二步:然后运行它
                    await scheduler.Start();
                    //第三步:定义作业并绑定到HelloJob类,HelloJob类实现IJob接口
                    IJobDetail job = JobBuilder.Create<HelloJob>()
                            .WithIdentity("job1", "group1")
                            //UsingJobData 可以用来传参数
                            .UsingJobData("appKey", "123456QWE")
                            .UsingJobData("appName", "小熊猫")
                            .UsingJobData("api", "https://www.baidu.com")
                            .Build();

                    //第四步:创建触发器。设定,执行一次作业。
                    ITrigger trigger = TriggerBuilder.Create()
                        .WithIdentity("trigger1", "group1") //指定唯一标识,触发器名字,和组名字
                                                            //这对于将作业和触发器组织成“报告作业”和“维护作业”等类别非常有用。
                                                            //作业或触发器的键的名称部分在组内必须是唯一的
                        .StartAt(DateBuilder.FutureDate(5, IntervalUnit.Second)) //可以设定在未来的 5 秒钟后触发    
                        .Build();

                    //第五步:作业与触发器组合,安排任务
                    await scheduler.ScheduleJob(job, trigger);

                    //第六步:创建任务监听,用来解决任务执行失败的情况. HelloJob类实现IJobListener接口
                    IJobListener jobListener = new HelloJob();

                    // 注: 任务监听是通过 IJobListener.Name 来区分的.以下逻辑避免多个任务监听情况下造成的监听被覆盖.
                    // a) 获取当前任务监听实例的名称.
                    var listener = scheduler.ListenerManager.GetJobListener(jobListener.Name);
                    // b) 通过job.Key 获取该任务在调度系统中的唯一实体
                    IMatcher<JobKey> matcher = KeyMatcher<JobKey>.KeyEquals(job.Key);
                    // c) 注意: 任务监听系统中已存在当前任务监听实例,与新添加任务监听的逻辑的区别.
                    if (listener != null)
                    {
                        // 如果已存在该任务监听实例,调用此方法,为该任务监听实例新增监听对象
                        scheduler.ListenerManager.AddJobListenerMatcher(jobListener.Name, matcher);
                    }
                    else
                        // 任务监听系统中不存在该任务监听实例,则调用此方法新增监听对象
                        scheduler.ListenerManager.AddJobListener(jobListener, matcher);

                    //创建触发器监听,触发器监听与任务监听同名也不影响
                    ITriggerListener triggerListener = new HelloJob();
                    var triListener = scheduler.ListenerManager.GetTriggerListener(triggerListener.Name);
                    IMatcher<TriggerKey> triMatcher = KeyMatcher<TriggerKey>.KeyEquals(trigger.Key);
                    if (triListener != null)
                    {
                        scheduler.ListenerManager.AddTriggerListenerMatcher(triggerListener.Name, triMatcher);
                    }
                    else
                        scheduler.ListenerManager.AddTriggerListener(triggerListener, triMatcher);

                    //可以设置关闭该调度
                    //await Task.Delay(TimeSpan.FromSeconds(5));
                    //await scheduler.Shutdown();
                }
                catch (SchedulerException se)
                {
                    Console.WriteLine(se);
                }
            }
        }

        //实现IJobListener 接口,实现 ITriggerListener 接口,这里和 IJob逻辑放在了一起
        public class HelloJob : IJob, IJobListener, ITriggerListener
        {
            private string appKey;
            private string appName;
            private string appApi;

            public string Name
            {
                get;
            }
            public HelloJob()
            {
                this.Name = this.GetType().ToString();
            }
            public HelloJob(string name)
            {
                this.Name = name;
            }
            public async Task Execute(IJobExecutionContext context)
            {
                JobKey jkey = context.JobDetail.Key;
                TriggerKey tKey = context.Trigger.Key;

                JobDataMap dataMap = context.MergedJobDataMap;
                appKey = dataMap.GetString("appKey");   //通过键值获取数据
                appName = dataMap.GetString("appName");
                appApi = dataMap.GetString("api");
                await Console.Error.WriteLineAsync(
                    string.Format("[{0}]开始推送:\nJobKey:{1}\nTriggerKey:{2}\nAppKey:{3} appName: {4} , and AppAPI: {5}"
                    , DateTime.Now.ToLongTimeString(), jkey, tKey, appKey, appName, appApi));
            }
            #region IJobListener
            public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
            {
                await Console.Error.WriteLineAsync(string.Format("[{0}]任务监听,name:{1}|任务执行失败重新执行。"
                    , DateTime.Now.ToLongTimeString(), Name));
                //任务执行失败,再次执行任务
                await Execute(context);
            }

            public async Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
            {
                await Console.Error.WriteLineAsync(string.Format("[{0}]任务监听,name:{1}|准备执行任务。"
                    , DateTime.Now.ToLongTimeString(), Name));
            }

            public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default(CancellationToken))
            {
                await Console.Error.WriteLineAsync(string.Format("[{0}]任务监听,name:{1}|任务执行完成。"
                    , DateTime.Now.ToLongTimeString(), Name));
            }
            #endregion

            #region ITriggerListener
            public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default(CancellationToken))
            {
                await Console.Error.WriteLineAsync(string.Format("[{0}]触发器监听,name:{1}|触发器触发成功。"
                    , DateTime.Now.ToLongTimeString(), trigger.Key.Name));
            }

            public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
            {
                await Console.Error.WriteLineAsync(string.Format("[{0}]触发器监听,name:{1}|触发器开始触发。"
                    , DateTime.Now.ToLongTimeString(), trigger.Key.Name));
            }

            public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken))
            {
                await Console.Error.WriteLineAsync(string.Format("[{0}]触发器监听,name:{1}|触发器触发失败。"
                    , DateTime.Now.ToLongTimeString(), trigger.Key.Name));
            }

            public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
            {
                await Console.Error.WriteLineAsync(string.Format("[{0}]触发器监听,name:{1}|可以阻止该任务执行,这里不设阻拦。"
                    , DateTime.Now.ToLongTimeString(), trigger.Key.Name));
                // False 时,不阻止该任务。True 阻止执行
                return false;
            }
            #endregion
        }
    }
}

Experimental results

As shown in the screenshot, this is performed only once. Observe: Trigger monitor priority> Priority task monitor

 
image

Part

Part I: job scheduling framework Quartz.NET-01- Getting Started

Thanks

Quartz.NET

Zhang Shanyou's blog



Author: Replay923
link: https: //www.jianshu.com/p/ef1b6d1e11b2
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11789940.html