Hangfire使用取消令牌

时间:2018-06-18 22:37:13

标签: c# hangfire

我有一个经常性的工作,根据环境/事件,我必须停止并删除特定的周期性作业及其正在运行的实例(它可能正在运行或不运行)。

删除经常性工作很容易。要从我学到的东西中停止正在运行的工作,我必须使用取消令牌。问题是:我如何坚持取消令牌?有没有将它存储在数据库中并在以后使用它?

非常感谢

2 个答案:

答案 0 :(得分:0)

我过去遇到过同样的问题,我找到了解决方法。 我已在下面为你编译了一些伪代码,我希望这会有所帮助。

public void DeleteRunningHangfireJob(string methodName)
    {
        if (!string.IsNullOrEmpty(methodName)) {
            var monitor = JobStorage.Current.GetMonitoringApi();

            var processingJobs = monitor.ProcessingJobs(0, int.MaxValue);
            var enqueuedJobs = monitor.EnqueuedJobs(0, int.MaxValue);

            processingJobs.Where(o => o.Value.Job.Method.Name == methodName).ToList().ForEach(x => { BackgroundJob.Delete(x.Key); });
            enqueuedJobs.Where(o => o.Value.Job.Method.Name == methodName).ToList().ForEach(x => { BackgroundJob.Delete(x.Key); });
        }
    }

答案 1 :(得分:0)

您提供给 BackgroundJob.Enqueue 的表达式只需要一个内部方法,将 CancellationToken 作为其参数之一。 Hangfire 将为您提供一个在收到取消信号时停止工作的工具。

    public void LongRunningMethod(CancellationToken token) { /* work done */ }
    
    // called like so - Hangfire replaces the "None" token for you
    BackgroundJob.Enqueue(() => LongRunningMethod(CancellationToken.None));

请参阅 Hangfire 文档:https://angular.io/guide/observables-in-angular