Quartz.Net中的长时间运行作业

问题描述:

我在Quartz.Net中有一份工作,它经常触发,有时会长时间运行,如果作业已经在运行,我该如何取消触发器?Quartz.Net中的长时间运行作业

更标准的方法是使用IInterruptableJob,请参阅http://quartznet.sourceforge.net/faq.html#howtostopjob。当然,这只是另一种说法,如果(!jobRunning)...

+0

只是一次实现IInterruptableJob的类的一个实例,或者是使用该类的Job? – 2009-09-15 08:49:36

+2

如果您只想一次只允许一个实例,那么IStatefulJob就是您的炸弹,http://quartznet.sourceforge.net/faq.html#howtopreventconcurrentfire。 IInterruptableJob只是给你一个标准的信号中断方法,你需要在工作方面做重大的事情(检查中断标志是否已经产生)。 – 2009-09-15 13:27:23

当作业开始时你能不能只是设置某种全局变量(jobRunning = true),并且一旦完成就将其恢复为假?

然后当触发器触发,只要运行你的代码,如果(jobRunning ==假)

+0

是的,通常最简单的解决方案是最好的。我已经实现了这一点,我虽然有一个实施的解决方案,这暂停了工作,直到第一次完成,但无论如何,这工作得很好! – 2009-09-10 14:38:45

您的应用可以从启动时的工作列表中删除本身并插入本身关机。

如今,您可以在触发器中使用“WithMisfireHandlingInstructionIgnoreMisfires”,并在作业中使用[DisallowConcurrentExecution]属性。

这是我的实现(使用MarkoL先前给出的链接上的建议)。

我只是想保存一些打字。

我是Quartz.NET的新手,所以拿下一串盐。

public class AnInterruptableJob : IJob, IInterruptableJob 
{ 

    private bool _isInterrupted = false; 

    private int MAXIMUM_JOB_RUN_SECONDS = 10; 

    /// <summary> 
    /// Called by the <see cref="IScheduler" /> when a 
    /// <see cref="ITrigger" /> fires that is associated with 
    /// the <see cref="IJob" />. 
    /// </summary> 
    public virtual void Execute(IJobExecutionContext context) 
    { 


     /* See http://aziegler71.wordpress.com/2012/04/25/quartz-net-example/ */ 

     JobKey key = context.JobDetail.Key; 

     JobDataMap dataMap = context.JobDetail.JobDataMap; 

     int timeOutSeconds = dataMap.GetInt("TimeOutSeconds"); 
     if (timeOutSeconds <= 0) 
     { 
      timeOutSeconds = MAXIMUM_JOB_RUN_SECONDS; 
     } 

     Timer t = new Timer(TimerCallback, context, timeOutSeconds * 1000, 0); 


     Console.WriteLine(string.Format("AnInterruptableJob Start : JobKey='{0}', timeOutSeconds='{1}' at '{2}'", key, timeOutSeconds, DateTime.Now.ToLongTimeString())); 


     try 
     { 
      Thread.Sleep(TimeSpan.FromSeconds(7)); 
     } 
     catch (ThreadInterruptedException) 
     { 
     } 


     if (_isInterrupted) 
     { 
      Console.WriteLine("Interrupted. Leaving Excecute Method."); 
      return; 
     } 

     Console.WriteLine(string.Format("End AnInterruptableJob (should not see this) : JobKey='{0}', timeOutSeconds='{1}' at '{2}'", key, timeOutSeconds, DateTime.Now.ToLongTimeString())); 

    } 


    private void TimerCallback(Object o) 
    { 
     IJobExecutionContext context = o as IJobExecutionContext; 

     if (null != context) 
     { 
      context.Scheduler.Interrupt(context.FireInstanceId); 
     } 
    } 

    public void Interrupt() 
    { 
     _isInterrupted = true; 
     Console.WriteLine(string.Format("AnInterruptableJob.Interrupt called at '{0}'", DateTime.Now.ToLongTimeString())); 
    } 
}