Quartz Scheduler 作业自动终止

Quartz Scheduler Job Auto Termination

如何创建在给定时间后自动终止的 Quartz Scheduler 作业(如果 运行 作业花费太多时间)?

Quartz 调度程序没有在给定时间后自行中断作业的内置功能。

如果您不想手动中断 Jobs(请参阅接口 InterruptableJob)(例如使用 rmi),您可以轻松地建立这样一个自动终止。

或者:

  1. 启动调度程序时,派生一个定期运行的守护线程并检查是否必须中断某些当前 运行 作业。例如,您可以使用 JobDataMap 来存储每个作业实例的最大执行时间。
  2. 每个 Job 都可以通过类似的方式控制其最大执行时间。

要从作业本身内部停止作业,最简单的方法是在特定时间后抛出异常。例如:

public class MyJob : IJob
{
    Timer _t;

    public MyJob()
    {
        TimeSpan maxRunningTime = TimeSpan.FromMinutes(1);
        _t = new Timer(delegate { throw new JobExecutionException("took to long"); }, null, (int) maxRunningTime.TotalMilliseconds,
            -1);
    }

    public void Execute(IJobExecutionContext context)
    {
        // do your word
        // destroy T before leaving

        _t = null;
    }
}

希望对您有所帮助:)