Quartz timer task framework demo

Begin to build an empty web project.

Create a new class QuartzFactory copy fiercely to get away.

  public class QuartzFactory : IJobFactory
    {
        private readonly IServiceProvider _serviceProvider;

        public QuartzFactory(IServiceProvider serviceProvider)
        {
            _serviceProvider = service provider;
        }

        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            var jobDetail = bundle.JobDetail;

            was job = (IJob) _serviceProvider.GetService (jobDetail.JobType);
            return job;
        }

        public void ReturnJob(IJob job)
        {
        }
    }

QuartzJob

public class QuartzJob : IJob
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        public async Task Execute(IJobExecutionContext context)
        {
            var JobKey = context.JobDetail.Key; // Get the job information 
            var triggerKey = context.Trigger.Key; // obtaining trigger information --jobWork2 --jobWork1 

            logger.info ($ " {} QuartzJob the DateTime.Now: ==> > automate \ R & lt \ {n-jobKey.Name} | {} triggerKey.Name \ R & lt \ n-. " );
             the await Task.CompletedTask;
        }
    }

QuartzService

  public static class QuartzService
    {
        #region single-tasking
         public  static  void StartJob <TJob> () the WHERE TJob: IJob
        {
          var scheduler = new StdSchedulerFactory().GetScheduler().Result;
 
          var job = JobBuilder.Create<TJob>()
            .WithIdentity("job")
            .Build();
 
          var trigger1 = TriggerBuilder.Create()
            .WithIdentity("job.trigger")
            .StartNow ()
            .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(5)).RepeatForever())
            .ForJob(job)
            .Build();
 
          scheduler.AddJob(job, true);
          scheduler.ScheduleJob(job, trigger1);
          scheduler.Start();
        }
        #endregion
 
        #region multitasking
         public  static  void StartJobs <TJob> () the WHERE TJob: IJob
        {
          var scheduler = new StdSchedulerFactory().GetScheduler().Result;
 
          var job = JobBuilder.Create<TJob>()
            .WithIdentity("jobs")
            .Build();
 
          var trigger1 = TriggerBuilder.Create()
            .WithIdentity("jobWork1")
            .StartNow ()
            .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(5)).RepeatForever())
            .ForJob(job)
            .Build();
 
          var trigger2 = TriggerBuilder.Create()
            .WithIdentity("jobWork2")
            .StartNow ()
            .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(11)).RepeatForever())
            .ForJob(job)
            .Build();
 
          var dictionary = new Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>>
          {
            {job, new HashSet<ITrigger> {trigger1, trigger2}}
          };
          scheduler.ScheduleJobs(dictionary, true);
          scheduler.Start();
        }
        #endregion
 
        #region 配置
        public static void AddQuartz(this IServiceCollection services, params Type[] jobs)
        {
          services.AddSingleton<IJobFactory, QuartzFactory>();
          services.Add (jobs.Select (job type => New ServiceDescriptor (job type, job type, ServiceLifetime.Singleton)));
 
          services.AddSingleton(provider =>
          {
            var schedulerFactory = new StdSchedulerFactory();
            var scheduler = schedulerFactory.GetScheduler().Result;
            scheduler.JobFactory = provider.GetService<IJobFactory>();
            scheduler.Start();
            return scheduler;
          });
        }
        #endregion 
    }
View Code

Reading a code in the code above

  var trigger2 = TriggerBuilder.Create()
            .WithIdentity("jobWork2")
            .StartNow ()
            .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(11)).RepeatForever())
            .ForJob(job)
            .Build();


WithIdentity ()
brackets strings that time will spread QuartzJob class,
I mainly use this string to determine the timing of a job you have to perform a certain task.

 

WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(11)).RepeatForever())

There's TimeSpan.FromSeconds (11) is the time your timing.

Several times every day also. CronScheduleBuilder.DailyAtHourAndMinute (16, 10)  

This is timed 16:10 to perform every day, of course, you copied these classes useless. Because it is the core task of the project is to be registered.

 


Startup Class
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc ();    // Register mvc service   
            services.AddQuartz ( typeof (QuartzJob));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // use as a logging tool NLog 
            loggerFactory.AddNLog ();
             // introduced Nlog profile 
            env.ConfigureNLog ( " Nlog.config " );

            QuartzService.StartJobs <QuartzJob> ();   // multi-tasking

            // QuartzService.StartJob <QuartzJob> ();   // single task 

            app.UseMvc (routes => {      // Open MVC 
                routes.MapRoute (
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}"
                    );
            });
        }

So that it can run.

 

Because I write a demo using a log Nlog.

 

 We can see a jobWork1 and 2 can be used to distinguish the task.

 

Guess you like

Origin www.cnblogs.com/ya-jun/p/11766122.html