.Net Core used Quartz.Net

Original: .Net Core used Quartz.Net

I. INTRODUCTION

  Quartz.Net is adapted from Java with C # from the Quartz, the latest version is 3.0.6, source code https://github.com/quartznet/quartznet . The main role is to do some periodic work or regular work. For example, 2:00 daily statistics for the previous day's data.

Second, the simple case

  To WebApi project, for example, the new WebApi project with VS scaffolding function.

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc();
     services.AddSingleton <ISchedulerFactory, the StdSchedulerFactory> (); // register the instance of ISchedulerFactory. 
 }
   [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly ISchedulerFactory _schedulerFactory;
        private IScheduler _scheduler;
        public ValuesController(ISchedulerFactory schedulerFactory)
        {
            this._schedulerFactory = schedulerFactory;
        }
        [HttpGet]
        public async Task<string[]> Get()
        { 
       // 1, the scheduling by the scheduler plant _scheduler
= the await _schedulerFactory.GetScheduler ();
       // 2, scheduler open
the await _scheduler.Start ();        //. 3, to create a trigger var Trigger = TriggerBuilder.Create () .WithSimpleSchedule (X => x.WithIntervalInSeconds ( 2 ) .RepeatForever ()) // performed once every two seconds .Build();        // 4, to create a task var jobDetail = JobBuilder.Create <MyJob> () .WithIdentity("job", "group") .Build();        / / 5, and trigger the task scheduler is bound to the await _scheduler.ScheduleJob (jobDetail, Trigger); return the await Task.FromResult ( new new String [] { " VALUE1 " , " value2 " }); }
}
public  class MyJob: IJob // create IJob implementation class, and implement Excute method.
    {
        public Task Execute(IJobExecutionContext context)
        {
      return Task.Run(() =>   {
  using (StreamWriter sw = new StreamWriter(@"C:\Users\Administrator\Desktop\error.log", true, Encoding.UTF8))   {   sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));   } }); } }

Output results:

2018-08-03 00-03-19
2018-08-03 00-03-20
2018-08-03 00-03-22
2018-08-03 00-03-24
2018-08-03 00-03-26

This Job above parameters is not performed, the parameters can be passed as parameters required by the following methods:

1, add the parameter values ​​in the Trigger

 var trigger3 = TriggerBuilder.Create()
                        .WithSimpleSchedule (X => x.WithIntervalInSeconds ( 2 ) .RepeatForever ()) // 2-second interval has been performed 
                        .UsingJobData ( " key1 " , 321 )   // Trigger parameter values by adding the 
                        .UsingJobData ( " key2 " , " 123 " )
                        .WithIdentity("trigger2", "group1")
                        .Build();

2, the parameter value is added in the Job

 IJobDetail job = JobBuilder.Create<MyJob>()
                                .UsingJobData ( " key1 " , 123 ) // parameter value by adding Job 
                                .UsingJobData ( " key2 " , " 123 " )
                                .WithIdentity("job1", "group1")
                                .Build();

Job parameter values ​​acquired by the following method

public  class MyJob: IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            var jobData = context.JobDetail.JobDataMap; // acquisition parameters of Job

            var TriggerData = context.Trigger.JobDataMap; // Get the Trigger parameter

            var Data = context.MergedJobDataMap; // Get Job parameters were combined and Trigger

            var value1= jobData.GetInt("key1");
            var value2= jobData.GetString("key2");

            var dateString = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");return Task.Run(() =>
            {
                using (StreamWriter sw = new StreamWriter(@"C:\Users\Administrator\Desktop\error.log", true, Encoding.UTF8))
                {
                    sw.WriteLine(dateString);
                }
            });
        }
    }

When Job as the parameter name and the parameter in the Trigger, acquiring parameters context.MergedJobDataMap, Trigger value overrides a value in the Job.

3, above the kind of situation that can adapt to the situation, the parameter values ​​unchanged. If this is the case, the parameter value is the value calculated after the first execution of the above process can not be used. The accumulated every two seconds to achieve an operation, now is an initial value of 0, if the value of the get operation in accordance with the above kind, always 0 + 1, always returns the value 1. To meet this situation, just add a characteristic [PersistJobDataAfterExecution].

    [PersistJobDataAfterExecution] // update the stored copy of JobDataMap JobDetail in order to perform the next task to receive an updated value instead of the original value stored 
    public  class MyJob: IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            var job data = context.JobDetail.JobDataMap;
            var trigger data = context.Trigger.JobDataMap;
            var data = context.MergedJobDataMap;

            var value1 = jobData.GetInt("key1");
            var value2 = jobData.GetString("key2");
            var value3 = data.GetString("key2");

            var dateString = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
            Random random = new Random();

            jobData [ " key1 " ] = Random.Next ( . 1 , 20 is ); // there is a key assignment, performed next time and then come in, the value of the updated value obtaining, instead of the original value 
            jobData [ " key2 " ] = dateString;

            return Task.Run(() =>
            {
                using (StreamWriter sw = new StreamWriter(@"C:\Users\Administrator\Desktop\error.log", true, Encoding.UTF8))
                {
                    sw.WriteLine($"{dateString} value1:{value1} value2:{value2}");
                }
                //context.Scheduler.DeleteJob(context.JobDetail.Key);
                //context.Scheduler.Shutdown();
            });
        }
    }

 Three, Quartz.Net composition

  There are three main components Quartz tasks (Job), the trigger (the Trigger) and scheduler (Schedule).

  3.1 Task

    Job is job execution, Job need to inherit IJob interface, the Execute method. Job parameters acquired from the parameter performed in the Execute method.

  3.2 Triggers

     Triggers are often used in two ways: SimpleTrigger trigger and trigger CronTrigger.

    SimpleTrigger: business can be simple, such as every few minutes, a few hours to trigger the execution, and limit the number of executions.

var trigger = TriggerBuilder.Create()
                       .WithSimpleSchedule(x => x.WithIntervalInSeconds(2).WithRepeatCount(5))//间隔2秒 执行6次
                       .UsingJobData("key1", 321)
                       .WithIdentity("trigger", "group")
                       .Build();

    CronTrigger: Cron expression contains seven fields within seconds timeshare weeks of May Day Month Date (optional).

  For example:

 var trigger = TriggerBuilder.Create()
                       .WithCronSchedule ( " 0 0 0 1 1? " ) // annual New Year's Day at 0:00 on January 1 trigger
                       .UsingJobData("key1", 321)
                       .UsingJobData("key2", "trigger-key2")
                       .WithIdentity("trigger4", "group14")
                       .Build();

"01510 * *? *" Trigger every day at 10:15 am  

Every 1 minute when the "00-514 * *?" 2:00 pm to 2:05 pm every day during  

  3.3 scheduler

    The task scheduler is binding and triggers, so that when the trigger is triggered to perform the task.

Guess you like

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