我在Quartz.Net上有一个工作,它经常触发,有时运行很长时间,如果作业已经运行,我如何取消触发器?

有帮助吗?

解决方案

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

其他提示

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

然后当触发器触发时,只需运行代码if(jobRunning == false)

您的应用可能会在启动时从作业列表中删除,并在关闭时自行插入。

现在你可以使用“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()));
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top