首页 > 解决方案 > Hangfire 使用取消令牌

问题描述

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

删除重复作业很容易。要停止正在运行的作业,据我所知,我必须使用取消令牌。问题是:如何保留取消令牌?有没有办法将其存储在数据库中并稍后使用?

标签: c#hangfire

解决方案


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

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); });
        }
    }

推荐阅读