Quartz.Net线程处理用到的两个Attribute

1.DisallowConcurrentExecution

 加到IJob实现类上,主要防止相同JobDetail并发执行。

 简单来说,现在有一个实现了IJob接口的CallJob,触发器设置的时间是每5s执行一次,但是由于执行过程的时间大于5s,在Quartz scheduler的下一次执行时间到了,那么就会开启另外一个线程执行CallJob,说着有点绕,来点代码吧。

 1                 Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };
 2               
 3                 IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
 4                 scheduler.Start();
 5                 IJobDetail job = JobBuilder.Create<CallJob>().WithIdentity("calljob", "call")
                      .UsingJobData("hello", 0)//先忽略,第二个特性用到
                      .Build();
6 //触发器 7 ITrigger trigger = TriggerBuilder.Create().WithIdentity("calljobtrigger", "call").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()).Build(); 8 scheduler.ScheduleJob(job, trigger); 9 Thread.Sleep(TimeSpan.FromSeconds(3000)); 10 scheduler.Shutdown();
 1  public class CallJob : IJob
 2     {
 3 
 4         public void Execute(IJobExecutionContext context)
 5         {
 6             int i = (int)context.JobDetail.JobDataMap["hello"];//先忽略,第二个特性用到
 7             Console.WriteLine("=====call======"+(i));
 8             Console.WriteLine("call【" + Thread.CurrentThread.ManagedThreadId + "" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
 9             i++;
10             context.JobDetail.JobDataMap.Put("hello", i);//先忽略,第二个特性用到
11             Thread.Sleep(8000);
12             Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "call执行完毕【" + Thread.CurrentThread.ManagedThreadId);
13 
14         }
15     }

  从代码中可以看到我们设置的trrigger是5秒执行一次,在CallJob的Execute中,让线程sleep 8s,这样就能模拟刚才说的情况了,先看下不加DisallowConcurrentExecution的结果

    

  第一张图是不加特性的,第二张图是加上特性的。图一中不难发现,线程10在休眠的时候,由于scheduler规划的trigger已经触发,会立即执行,不去管上次任务是否执行完成,从而出现了同一个Job并行。图二就不会出现并行的情况,当第一次任务还没有执行完成的时候,即使规划的trigger的触发时间到了也不会立即执行,而是等待上次任务完成再执行,依次顺延,保证了相同JobDetail串行。说明一下DisallowConcurrentExecution是禁止相同JobDetail同时执行,而不是禁止多个不同JobDetail同时执行。建议加上该特性,防止由于任务执行时间太长,长时间占用资源,导致其它任务堵塞。

2.PersistJobDataAfterExecution

 加到IJob实现类上,主要表示当正常执行完Job后, JobDataMap中的数据应该被改动, 以被下一次调用时用。还是上面的代码,只是将特性DisallowConcurrentExecution换成了PersistJobDataAfterExecution,特别注意代码中【先忽略】部分。

 当不使用PersistJobDataAfterExecution特性时,每次取出来的hello键值对的value始终都是0,也就是说每次执行 JobDataMap中的数据都是全新的一份,加上特性PersistJobDataAfterExecution之后,就会出现数据共享。没加特性的结果可以看上图,加上之后看下图。

  注意当使用【PersistJobDataAfterExecution】特性时, 为了避免并发时, 存储数据造成混乱, 强烈建议把【DisallowConcurrentExecution】特性也加上。

  本人很菜,欢迎拍砖。

 

原文地址:https://www.cnblogs.com/lb12081116/p/6929485.html