Uwl.Admin open-source framework (b) Asp.Net Core2.0 QuartzNet based task management system

Uwl.Admin open source framework based QuartzNet timing of the task module implemented

 

Quartz.NET official website address: https://www.quartz-scheduler.net/

 

Quartz.NET document Address: https://www.quartz-scheduler.net/documentation/index.html

Quartz.NETIs an open source job scheduling framework is OpenSymphonyof Quartz APIthe .NET transplantation, it is written using C #, may be used winform, and asp.netapplications. It offers great flexibility without sacrificing simplicity. You can use it to create simple or complex schedules for the implementation of a job. It has many features, such as: database support, clustering, plug-ins, support cron-likeexpressions and so on.

Now Quartz.NET3.0has support for Asp.Net Core3.0 new features are as follows:

new function

  • With asynchronous / task-based jobs waiting to support internal asynchronous / waiting way work
  • Support .NET Core / netstandard 2.0 and .NET Framework 4.5.2 and later
  • By provider name SQLite-Microsoftsupport Microsoft.Data.Sqlite, the old provider SQLitestill valid
  • Increased SQL Servermemory optimization tables and Quartz.Impl.AdoJobStore.UpdateLockRowSemaphoreMOTinitial support
  • Common.LoggingDeleted from the correlation in
  • From ILMergedeletion process C5 collection is no longer needed
  • Add urgent job scheduling validation of XML documents in the plug-in start-up support
  • In TimeZoneUtiladd support for additional custom parser function in the time zone

Variety

  • Job and plug assembly are in separate NuGetpackages Quartz.Jobsand Quartz.Pluginsin
  • ADO.NET provider name has been simplified, no provider name version, for example,SqlServer-20 => SqlServer
  • API methods have been re-used, primarily IReadOnlyCollection, which hides two HashSets trumpet and List
  • LibLogIt has been hidden inside (ILog, etc.), as it was originally intended as
  • SimpleThreadPoolDisappeared, the old has gone threads
  • Scheduler task-based method has been changed to, remember waiting for them
  • IJobThe interface now returns a task
  • Some IListproperties have been changed IReadOnlyListto correctly reflect the intent
  • SQL Server CESupport has been removed
  • DailyCalendarNow the date and time for the date of exclusion, and has ISetinterfaces to access them
  • IObjectSerializerThere are new methods void Initialize()must be implemented
  • IInterruptableJobCanceled contextCancellationToken

Quartz API key interfaces and classes are :

  • IScheduler - The main API to interact with the scheduler.
  • IJob - You want the interface component performed by the scheduler implementation.
  • IJobDetail - for defining the job instance.
  • ITrigger - a timetable for the implementation of the component definition of Job.
  • JobBuilder - for defining / job instance build definition JobDetailinstance.
  • TriggerBuilder - for defining / build triggers Examples

A, Quartz.NET basic use

  1, the new project Uwl.QuartzNet.JobCenter library, using the Quartz NuGet add, or use references Package Manager, the command is as follows:

  Install-Package Quartz

  2, Uwl.QuartzNet.JobCenter library's role:

   Uwl.QuartzNet.JobCenter library is scheduled tasks management center, here I put a piece of code, and hold too much specific implementation can be downloaded Uwl.Admin.Core project to see 
    /// <the Summary>
        /// open tasks scheduling
        /// </ Summary>
        /// <Returns> </ Returns>
        public the async the Task <JobResuleModel> StartScheduleAsync ()
        {
            var new new JobResuleModel Result = ();
            the try
            {
                IF (! this._scheduler.Result.IsStarted)
                {
                    // wait for the completion of the task to run
                    the await this._scheduler.Result.Start ();
                    the await Console.Out.WriteLineAsync ( "task scheduler open!");
                    result.IsSuccess = to true;
                    result.Message = $ "Task scheduling open success ";
                    Result return;
                }
                the else
                {
                    result.IsSuccess = to false;
                    result.Message $ = "scheduling has been turned";
                    return Result;
                }
            }
            the catch (Exception)
            {
                the throw;
            }
        }

A flip-flop type

  1, SimpleTrigger trigger (simple flip-flop)

Asp.Net Core2.0 QuartzNet based task management system

Quartz.NET official website address: https://www.quartz-scheduler.net/

Quartz.NET document Address: https://www.quartz-scheduler.net/documentation/index.html

Quartz.NETIs an open source job scheduling framework is OpenSymphonyof Quartz APIthe .NET transplantation, it is written using C #, may be used winform, and asp.netapplications. It offers great flexibility without sacrificing simplicity. You can use it to create simple or complex schedules for the implementation of a job. It has many features, such as: database support, clustering, plug-ins, support cron-likeexpressions and so on.

Now Quartz.NET3.0has support for Asp.Net Core3.0 new features are as follows:

new function

  • With asynchronous / task-based jobs waiting to support internal asynchronous / waiting way work
  • Support .NET Core / netstandard 2.0 and .NET Framework 4.5.2 and later
  • By provider name SQLite-Microsoftsupport Microsoft.Data.Sqlite, the old provider SQLitestill valid
  • Increased SQL Servermemory optimization tables and Quartz.Impl.AdoJobStore.UpdateLockRowSemaphoreMOTinitial support
  • Common.LoggingDeleted from the correlation in
  • From ILMergedeletion process C5 collection is no longer needed
  • Add urgent job scheduling validation of XML documents in the plug-in start-up support
  • In TimeZoneUtiladd support for additional custom parser function in the time zone

Variety

  • Job and plug assembly are in separate NuGetpackages Quartz.Jobsand Quartz.Pluginsin
  • ADO.NET provider name has been simplified, no provider name version, for example,SqlServer-20 => SqlServer
  • API methods have been re-used, primarily IReadOnlyCollection, which hides two HashSets trumpet and List
  • LibLogIt has been hidden inside (ILog, etc.), as it was originally intended as
  • SimpleThreadPoolDisappeared, the old has gone threads
  • Scheduler task-based method has been changed to, remember waiting for them
  • IJobThe interface now returns a task
  • Some IListproperties have been changed IReadOnlyListto correctly reflect the intent
  • SQL Server CESupport has been removed
  • DailyCalendarNow the date and time for the date of exclusion, and has ISetinterfaces to access them
  • IObjectSerializerThere are new methods void Initialize()must be implemented
  • IInterruptableJobCanceled contextCancellationToken

Quartz API key interfaces and classes are :

  • IScheduler - The main API to interact with the scheduler.
  • IJob - You want the interface component performed by the scheduler implementation.
  • IJobDetail - for defining the job instance.
  • ITrigger - a timetable for the implementation of the component definition of Job.
  • JobBuilder - for defining / job instance build definition JobDetailinstance.
  • TriggerBuilder - for defining / build triggers Examples

A, Quartz.NET basic use

1, the new Asp.Net Core project, using the Quartz NuGet add, or use references Package Manager, the command is as follows:
Install-Package Quartz

 If you want to add JSON serialization, just add in the same way Quartz.Serialization.Jsonpackage.

2, a simple example, as follows:
using Five.QuartzNetJob.ExecuteJobTask.Service;
using Quartz;
using Quartz.Impl; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Threading.Tasks; namespace Five.QuartzNetJob.Web.Controllers { public class TestTask { public async Task StartTestAsync() { try { // 从工厂中获取调度程序实例 NameValueCollection props = new NameValueCollection { { "quartz.serializer.type", " Binary " }}; the StdSchedulerFactory Factory = new new the StdSchedulerFactory (The props); IScheduler Scheduler = the await factory.GetScheduler (); // open scheduler the await scheduler.Start (); // definition of the job, and bind it to us the implementation class IJob job = JobBuilder.Create IJobDetail <HelloJob> () .WithIdentity ( " the jobs that job1 ", " named group1 " ) .build (); // trigger job run immediately, and then repeated every 10 seconds, an infinite loop ITrigger trigger = TriggerBuilder.Create () .WithIdentity ( " trigger1 ", " named group1 " ) .StartNow () .WithSimpleSchedule (X =>.WithIntervalInSeconds the X-( 10 ) .RepeatForever ()) .build (); // tell Quartz use our triggers to schedule jobs the await scheduler.ScheduleJob (the Job, the Trigger); // wait 60 seconds await Task.Delay (TimeSpan. FromSeconds ( 60 )); // Close the scheduler the await scheduler.shutdown ();} the catch (SchedulerException SE) { the await Console.Error.WriteLineAsync (se.ToString ());}}}}

 TestJobOne reads as follows:

using Quartz;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Uwl.Common.Cache.RedisCache;
using Uwl.Common.Subscription;
using Uwl.Data.Server.MenuServices;

namespace Uwl.ScheduledTask.Job
{
    public class TestJobOne : IJob
    {
        private readonly IRedisCacheManager _redisCacheManager;
        private readonly IMenuServer _menuServer;
        public TestJobOne(IRedisCacheManager redisCacheManager,IMenuServer menuServer)
        {
            this._redisCacheManager = redisCacheManager;
            this._menuServer = menuServer;
        }
        Task the Execute the async public (IJobExecutionContext context)
        {
            // Job record time
            Stopwatch Stopwatch = new new Stopwatch ();
            stopwatch.Start ();
            
            the await Console.Out.WriteLineAsync ( "I have a job Redis injection test");
            var List = _menuServer.GetMenuList the await ();
            the await Console.Out.WriteLineAsync ( "the total number of menu list" + list.Count.ToString ());
            stopwatch.Stop ();
            the await Console.Out.WriteLineAsync ( "execution time" + stopwatch .Elapsed.TotalMilliseconds);
            // iF (stopwatch.Elapsed.TotalMilliseconds> 0)
            // {
            // // written to the log table and the performance monitoring whether an error occurred
            //}
        }
    }
}

Second, the Trigger Type

 1, SimpleTrigger trigger (simple flip-flop)

SimpleTriggerThe properties include: the start time and end time, repetition interval and repetition count. Repetition count may be zero or a positive integer constant value SimpleTrigger.RepeatIndefinitely. Attribute must be a repeat interval TimeSpan.Zeroor a positive TimeSpanvalue. Please note that the repeat interval to 0 causes "Repeat Count" trigger trigger occur simultaneously. SimpleTriggerExamples of use TriggerBuilder(for the primary property triggers) and the WithSimpleScheduleextension method (for SimpleTriggerspecific attributes) construct.

Establish a specific time trigger need to be repeated, as follows:

   /// <summary>
        /// 创建SimpleTrigger触发器(简单触发器)
        /// </summary>
        /// <param name="sysSchedule"></param>
        /// <param name="starRunTime"></param>
        /// <param name="endRunTime"></param>
        /// <returns></returns>
        private ITrigger CreateSimpleTrigger(SysSchedule sysSchedule)
        {
            if(sysSchedule.RunTimes>0)
            {
                ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity(sysSchedule.Id.ToString(), sysSchedule.JobGroup)
                .StartAt(sysSchedule.BeginTime.Value)
                .EndAt(sysSchedule.EndTime.Value)
                .WithSimpleSchedule(x =>
                x.WithIntervalInSeconds(sysSchedule.IntervalSecond)
                .WithRepeatCount(sysSchedule.RunTimes)).ForJob(sysSchedule.Id.ToString(), sysSchedule.JobGroup).Build();
                return trigger;
            }
            else
            {
                ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity(sysSchedule.Id.ToString(), sysSchedule.JobGroup)
                .StartAt(sysSchedule.BeginTime.Value)
                .EndAt(sysSchedule.EndTime.Value)
                .WithSimpleSchedule(x =>
                x.WithIntervalInSeconds(sysSchedule.IntervalSecond)
                .RepeatForever ()) ForJob (sysSchedule.Id.ToString (), sysSchedule.JobGroup) .build ();.
                Return Trigger;
            }
            // trigger job run immediately, and then repeated every 10 seconds, an infinite loop
            
        }

So simple task scheduling using SimpleTriggercompletely sufficient, if SimpleTriggerstill can not meet your needs please read on.

2, CronTrigger trigger

If you need a calendar based on a similar concept, rather than a precisely specified SimpleTriggerwork scheduling time interval, CronTriggersusually higher than the SimpleTriggermore useful.

Use CronTrigger, a you can specify the schedule start on Wednesday between 9:00 to 10:00, for example, "every Friday at noon" or "each weekday and 9:30" Weekly, or "every 5 minutes" and Friday. "

Even so, just SimpleTriggeras CronTriggerthere is a startTimethat specifies the effective time schedule, there is a (optional) endTimethat specifies the time schedule should be stopped.

Here it is not described in detail Cron.

Cron Expression Builder Online: http://cron.qqe2.com/

Cron expression Details: https://www.jianshu.com/p/e9ce1a7e1ed1

   /// <Summary>
        /// Cron type flip-flop created
        /// </ Summary>
        /// <param name = "m"> </ param>
        /// <Returns> </ Returns>
        Private ITrigger CreateCronTrigger (SYSSCHEDULE SYSSCHEDULE)
        {
            // job trigger
            return TriggerBuilder.Create ()
                   .WithIdentity (sysSchedule.Id.ToString (), sysSchedule.JobGroup)
                   .StartAt (sysSchedule.BeginTime.Value) // start time
                   .EndAt (sysSchedule.EndTime .Value) // end the data
                   .WithCronSchedule (sysSchedule.Cron) // specify cron expression
                   .ForJob (sysSchedule.Id.ToString (), sysSchedule.JobGroup) // job name
                   .Build ();
        }

Summary (very important):  Quartz.NETVersion 3.0 with version api interface to change before is not great. Just add in version 3.0.7 asynchronous call, and support the .net core. Examples of simple task scheduling using the official website can satisfy the requirement, the time dependency injection should be rewritten IJobFactory plant, rewriting NewJob, ReturnJob IJobFactory method in factory;

Specific code implementation

   /// <summary>
        /// 注入反射获取依赖对象
        /// </summary>
        private readonly IServiceProvider _serviceProvider;
        public IOCJobFactory(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }
        /// <summary>
        /// 实现接口Job
        /// </summary>
        /// <param name="bundle"></param>
        /// <param name="scheduler"></param>
        /// <returns></returns>
        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            try
            {

     This position needs to be recreated _serviceProvider.CreateScope (); container, or will be prompted Job / there is a situation you can not find is also injected But Job can not be executed, so this position should be re-bedstead container instance,
                var serviceScope = _serviceProvider .CreateScope ();
                var = serviceScope.ServiceProvider.GetService Job (bundle.JobDetail.JobType) AS IJob;
                return Job;
                // var = _serviceProvider.GetService Job (bundle.JobDetail.JobType) AS IJob;
                // Job return;

            }
            the catch (Exception E)
            {
                the throw E;
            }
        }

        public void ReturnJob (IJob Job)
        {
            var Disposable Job AS = the IDisposable;
            IF (! = null Disposable)
            {
                disposable.Dispose();
            }
            
        }

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/pual13/p/12010047.html