Method of assigning value to main thread form control used by Quartz timer

Keywords: C#

Recently, when writing an import tool, I used a new thing called Quartz timer. Some timers have Quartz basically, so I used Quartz to write the code and record it.

1. First you need to refer to the GuGet package, search for 'quartz', download and install it to the program.

2. Code directly, create job, trigger and other methods

Job parameters: job.JobDataMap.Put("AutoImport", formInstance); here, 'AutoImport' is an instance of the main form

  // 1.establish scheduler References to
                ISchedulerFactory schedFact = new StdSchedulerFactory();
                sched = await schedFact.GetScheduler();
                //2.start-up scheduler
                await sched.Start();
                // 3.establish job
                IJobDetail job = JobBuilder.Create<DoWork>()
                        .WithIdentity("job5", "group5")
                job.JobDataMap.Put("AutoImport", formInstance);    //job parameters

                //   4.establish trigger
                ITrigger trigger = TriggerBuilder.Create()
                      .WithIdentity("trigger5", "group5")
                      .WithSimpleSchedule(x => x
                        .WithIntervalInMinutes(int.Parse(jiange))     //Next execution time
                        .RepeatForever())               //Execute forever

                // 5.use trigger Plan and execute tasks job
                await sched.ScheduleJob(job, trigger);


3. Execute the method in the job, get the main form instance from the job, and modify the value of the control through the instance.

   public class DoWork : IJob
            public virtual async Task Execute(IJobExecutionContext context)
                AutoImport au = (AutoImport)context.JobDetail.JobDataMap.Get("AutoImport");  //Get the parameters from the job
          //Modify the value of the control in the main form
         au.datetime_startime.Value = DateTime.Parse(nexttime);   
         au.lab_msg.Text = "Waiting for next start time..." + nexttime;
          await Task.CompletedTask;

This solves the problem of modifying the value of the main form control.

About the other methods of Quartz, brothers and children can baidu themselves, a lot of data demo for you to learn!!

Posted by Bozebo on Fri, 15 May 2020 07:19:01 -0700