挂钩 Quartz.net 中的关闭方法

Hook to shutdown method in Quartz.net

我有一个很长的 运行 作业,它迭代超过百万行来完成一些任务。 如果为作业请求关闭,我希望能够在此迭代的中间停止。基本上我有这个

public class MyLongRunningJob : IJob
{   
    public void Execute(IJobExecutionContext context)
    {
        var rows = GetAllRows();
        foreach(var row in rows)
        {
            DoSomething(row);
        }
    }
}

我想要这样的东西

public class MyLongRunningJob : IJob
{
    bool _stop = false;
    public void Execute(IJobExecutionContext context)
    {
        var rows = GetAllRows();
        foreach(var row in rows)
        {
            if(_stop) break;
            DoSomething(row);
        }
    }
}

由于 Execute 方法可能需要 1 个多小时,我想在某个时候将 _stop 设置为 true,当我调用调度程序的 Shutdown 时,我无法在 IJob 或 Scheduler 上找到任何要连接的内容。

这个长 运行 作业是我的 windows 服务上唯一执行的任务,希望尽快从 Execute 方法退出。

windows 服务是带有 Autofac 的 TopShelf 服务,看起来像

public class Service : IService
{
    private readonly IScheduler _scheduler;

    public Service(IScheduler scheduler)
    {
        _scheduler = scheduler;
    }

    public void Start()
    {
        _scheduler.Start();
    }

    public void Stop()
    {
        _scheduler.Shutdown();
    }
}

所以我正在阅读 Quartz。我以前从未使用过它,但这个帖子很有趣 Async/Await Support

看完之后,我注意到目前的想法是使用继承IJobIInterruptableJob

这允许调度程序调用中断方法以允许您停止代码 "nicely"。来自该界面上的文档:

The means of actually interrupting the Job must be implemented within the itself (the method of this interface is simply a means for the scheduler to inform the that a request has been made for it to be interrupted). The mechanism that your jobs use to interrupt themselves might vary between implementations. However the principle idea in any implementation should be to have the body of the job's periodically check some flag to see if an interruption has been requested, and if the flag is set, somehow abort the performance of the rest of the job's work. An example of interrupting a job can be found in the source for the class Example7's DumbInterruptableJob It is legal to use some combination of and synchronization within and in order to have the method block until the signals that it has noticed the set flag.

希望对您有所帮助。