DotNetCore cross-platform ~ Quartz scheduled single task, dotnetcorequartz

Source: Internet
Author: User

DotNetCore cross-platform ~ Quartz scheduled single task, dotnetcorequartz

I wrote an article titled DotNetCore cross-platform ~ The Gospel of Quartz hot deployment ~ Monitoring folder changes. Today, the framework is optimized to support external triggering, and external parameters are input in the form of JobDataMap, and then used in our Job, it is called a parameterized task.

Quartz application scenarios:

The External Trigger task mentioned today refers to the first type, that is, it will be executed only once at a certain time point in the future. Let's talk about the idea. For a job of this kind, a subclass of JobBase, it needs to overwrite the IsSingle attribute, set the value to 1 to indicate a single task, and then it will be executed immediately after Quartz is started, after the task is completed, destroy it!

Use Case: You can publish some methods in the quartz scheduling center, so that your Job is executed based on a certain time point and parameter, and the execution stops once, in this way, our scheduling becomes more flexible.

Added the IsSingle attribute for a single task.

[DisallowConcurrentExecution ()] public abstract class JobBase: ISchedulingJob {# region Properties /// <summary> // cancel the resource /// </summary> public CancellationTokenSource CancellationSource => new CancellationTokenSource (); /// <summary> /// execution plan, except for the JOB that is executed immediately, other jobs need to implement it /// </summary> public virtual string Cron => "*****? "; /// <Summary> /// whether the task is a single task. If the value is black, the value false /// </summary> public virtual bool IsSingle => false; /// <summary> /// Job name. The default value is the current class name /// </summary> public virtual string JobName => GetType (). name; // <summary> // timeout (ms) of Job execution ), the default value is 5 minutes. // </summary> public virtual int JobTimeout => 5*60*1000; # endregion Properties # region Methods // <summary> // The specific class of the Job to implement its own logic // </summary> protected abstract void E XcuteJob (IJobExecutionContext context, CancellationTokenSource cancellationSource); // <summary> // when a job times out, it will be triggered, you can send some notification emails, etc. /// </summary> /// <param name = "arg"> </param> private void CancelOperation (object arg) {CancellationSource. cancel (); StdSchedulerFactory. getdefaschscheduler (). result. interrupt (new JobKey (JobName); Console. writeLine (JobName + "Job execution timeout, canceled, waiting for the next scheduling... ") ;}# endregion Meth Ods # region IJob member public Task Execute (IJobExecutionContext context) {Timer timer = null; try {timer = new Timer (CancelOperation, null, JobTimeout, Timeout. infinite); Console. writeLine (DateTime. now. toString () + "{0} This Job starts execution", context. jobDetail. key. name); if (context. jobDetail. jobDataMap! = Null) {foreach (var pa in context. jobDetail. jobDataMap) Console. writeLine ($ "JobDataMap, key: {pa. key}, value: {pa. value} ") ;}excutejob (context, CancellationSource);} catch (Exception ex) {Console. writeLine (this. getType (). name + "error:" + ex. message);} finally {if (timer! = Null) timer. Dispose ();} return Task. CompletedTask ;}# endregion}

Uniform method for adding to Job Queue

In our previous zmanager manager, we needed to add support for a single task. In this case, we added the task to the quartz code for reconstruction and extracted it into the method.

/// <Summary> /// Add the type to the Job Queue // </summary> /// <param name = "type"> type </param> // /<param name = "dt"> time point </param> // <param name = "param"> parameter </param> private static void jow.quartz (Type type, dateTimeOffset dt, Dictionary <string, object> param = null) {var obj = Activator. createInstance (type); if (obj is ISchedulingJob) {var tmp = obj as ISchedulingJob; string cron = tmp. cron; string name = tmp. jo BName; var cancel = tmp. CancellationSource; var jobDetail = JobBuilder. Create (type). WithIdentity (name). Build (); if (param! = Null) foreach (var dic in param) jobDetail. jobDataMap. add (dic. key, dic. value); ITrigger jobTrigger; if (tmp. isSingle) {jobTrigger = TriggerBuilder. create (). withIdentity (name + "Trigger "). startAt (dt ). build ();} else {jobTrigger = TriggerBuilder. create (). withIdentity (name + "Trigger "). startNow (). withCronSchedule (cron ). build ();} StdSchedulerFactory. getdefaschscheduler (). result. scheduleJob (jobDetail, jobTrigger, cancel. token); LoggerInfo ($ "-> task module {name} is loaded... ", ConsoleColor. yellow );}}

Public parameter Interface

If you want to trigger this single task again, you can publish a method in QuartzManager to add a new Job to the current SchedulerFactory. This method is very simple, you can provide a default time policy. For example, if it is executed after 1 minute by default, you can also control the time by yourself.

/// <Summary> /// the task is executed once in 1 minute. // </summary> /// <param name = "type"> </param> /// <param name = "job"> </param> /// <param name = "param"> </param> public static void SignalJob (Type type Type, dictionary <string, object> param) {SignalJob (type, DateTimeOffset. now. addSeconds (10), param );} /// <summary> /// the task is executed once after a certain time // </summary> /// <param name = "type"> </param> /// <param name = "job"> </param> /// <param name = "offset"> </param> /// <param name = "param"> </param> public static void SignalJob (Type type, dateTimeOffset offset, Dictionary <string, object> param) {jow.quartz (type, offset );}

Now, a job scheduling center is more complete and developers can use it easily. They only need to inherit JobBase or implement the ISchedulingJob interface, which is very flexible!

Thank you for reading this article!

Quartz, dotnet core, we are still on the way to study!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.