对于hangfire 可以使用JobFilterAttribute, IClientFilter, IServerFilter 来自定义filter 实现该功能
public class DisableMultipleQueuedItemsFilter : JobFilterAttribute, IClientFilter, IServerFilter
{
/// <summary>
/// key: 定时任务的name
/// value: 具体的jobId
/// </summary>
public ConcurrentDictionary<string, string> RecurringIdleDic = new ConcurrentDictionary<string, string>();
public void OnCreated(CreatedContext context)
{
//var recurringJobId = context.Items("RecurringJobId");
RecurringIdleDic.TryAdd(context.Job.Type.Name, context.JobId);
}
public void OnCreating(CreatingContext context)
{
var recurringJobId = context.GetJobParameter<string>("RecurringJobId");
if (RecurringIdleDic.TryGetValue(recurringJobId, out var jobId))
{
context.Canceled = true;
}
}
public void OnPerformed(PerformedContext context)
{
var recurringJobId = context.GetJobParameter<string>("RecurringJobId");
RecurringIdleDic.TryRemove(new KeyValuePair<string, string>(recurringJobId, context.JobId));
}
public void OnPerforming(PerformingContext context)
{
}
}