Quartz.Net use

Quartz.Net use

Tags: Quartz.Net


In recent work, notifications and messages need to be sent regularly at different times and under different conditions, and the System.Timers.Timerimplementation was initially used. Although it is simple to use, with the increase of tasks that need to be processed regularly, consider the System.Timers.Timerfollowing disadvantages:

  • Timer has no persistence mechanism;
  • The scheduling of Timer is not flexible, it can only be triggered regularly, and the trigger time point cannot be freely configured;
  • Timer cannot use the thread pool, and each Timer needs to start a thread;
  • The tasks in each Timer are executed serially, and only one task can be executed at the same time. The failure of the previous task to execute will affect the execution of subsequent tasks;

The Quartz.Netfollowing advantages can solve the above problems

  • Flexible use, there are multiple ways of use ( eg XMLconfiguration tasks,), and can be mixed;
  • Support clustering, job grouping, and job remote management;
  • Customizable and fine-grained time management;
  • Database support and persistence.

Install

  • by NuGetinstallingQuartz.Net

illustrate

  • Each task needs to inherit the interface IJoband implement Execute(IJobExecutionContext context)it, and this method Jobneeds to do specific processing for each task;

code example

  • Code to create job example
  private static void Main(string[] args)
        {
            try
            {
                WatchFile();
                var fileName = Path.Combine(Environment.CurrentDirectory, "log4config.config");
                XmlConfigurator.ConfigureAndWatch(new FileInfo(fileName));
                StdSchedulerFactory factory = new StdSchedulerFactory();
                IScheduler scheduler = factory.GetScheduler();
                // 启动任务
                scheduler.Start();
                // 创建Job,可通过JobDataMap传递数据
                IJobDetail job = JobBuilder.Create<HelloJob>()
                    .WithIdentity("job1", "group1")
                    .UsingJobData("jobSays", "Hello World!")
                    .UsingJobData("myFloatValue", 3.141f)
                    .Build();
                //创建trigger
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "group1")
                    .StartNow()
                    .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())
                    .Build();
                //把job,trigger加入调度器
                scheduler.ScheduleJob(job, trigger);
                //关闭调度器
                scheduler.Shutdown();
            }
            catch (Exception ex)
            {
                LogHelper.Error("Main" + ex);
            }
            Console.WriteLine("Press any key to close the application");
            Console.ReadKey();
        }
    public class HelloJob : IJob
    {
        public void  Execute(IJobExecutionContext context)
        {
            JobKey key = context.JobDetail.Key;
            //获取执行的数据
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            string jobSays = dataMap.GetString("jobSays");
            float myFloatValue = dataMap.GetFloat("myFloatValue");
             Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);

        }
    }
    pub    
  • XMLway to configure the Job、Triggercode example
    1) in the file quartz_jobs.xmlfor configuration Joband configuration file example:Trigger
<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
  <processing-directives>
    <overwrite-existing-data>true</overwrite-existing-data>
  </processing-directives>
  <schedule>
    <job>
      <name>CommonIMRemindJob</name>
      <group>IMRemindJob</group>
      <description>IMRemindJob</description>
      <job-type>NXIN.Qlw.JobServices.CommonIMRemindJobService,NXIN.Qlw.JobServices</job-type>
      <durable>true</durable>
      <recover>true</recover>
    </job>
    <trigger>
      <simple>
        <name>CommonIMRemindTrigger</name>
        <group>IMRemindJob</group>
        <description>CommonIMRemindTrigger</description>
        <job-name>CommonIMRemindJob</job-name>
        <job-group>IMRemindJob</job-group>
        <misfire-instruction>SmartPolicy</misfire-instruction>
        <repeat-count>-1</repeat-count>
        <repeat-interval>300000</repeat-interval>
      </simple>
    </trigger>
  </schedule>
</job-scheduling-data>
2)实现示例
  private static void InitScheduler()
        {
            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer", "binary" }
                };

                XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());

                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                IScheduler scheduler = factory.GetScheduler();
                processor.ProcessFileAndScheduleJobs("~/quartz_jobs.xml", scheduler);
                scheduler.Start();
            }
            catch (SchedulerException se)
            {
                LogHelper.Error("/Main/RunProgramRunExample" + se);
            }
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324699237&siteId=291194637