解决方法:在执行的任务方法前加上Mutex特性即可,如果作业未完成,新作业开启的话,新作业会放入计划中的作业队列中,直到前面的作业完成。
必须使用Hangfire.Pro.Redis
和 Hangfire.SqlServer 作为数据库。
参考:https://github.com/HangfireIO/Hangfire/issues/1053
[Mutex("DownloadVideo")] public async Task DownloadVideo() {
}
Mutex特性代码如下:
using System; using System.Collections.Generic; using System.Linq; using Hangfire.Common; using Hangfire.States; using Hangfire.Storage; namespace Hangfire.Pro { /// <summary> /// Represents a background job filter that helps to disable concurrent execution /// without causing worker to wait as in <see cref="Hangfire.DisableConcurrentExecutionAttribute"/>. /// </summary> public class MutexAttribute : JobFilterAttribute, IElectStateFilter, IApplyStateFilter { private static readonly TimeSpan DistributedLockTimeout = TimeSpan.FromMinutes(1); private readonly string _resource; public MutexAttribute(string resource) { _resource = resource; RetryInSeconds = 15; } public int RetryInSeconds { get; set; } public int MaxAttempts { get; set; } public void OnS