30
loading...
This website collects cookies to deliver better user experience
EnqueuedState
.ScheduledState
to the EnqueuedState
and using it to enqueue the job to the correct queue.using System;
using Hangfire.States;
using Newtonsoft.Json;
public sealed class ScheduledQueueState : ScheduledState
{
public ScheduledQueueState(TimeSpan enqueueIn)
: this(DateTime.UtcNow.Add(enqueueIn), null)
{
}
public ScheduledQueueState(DateTime enqueueAt)
: this(enqueueAt, null)
{
}
[JsonConstructor]
public ScheduledQueueState(DateTime enqueueAt, string queue)
: base(enqueueAt)
{
this.Queue = queue?.Trim();
}
public string Queue { get; }
}
ScheduledState
and add a Queue
property while maintaining JSON serialization compatibility. Next, we need to take advantage of this new property when moving into the EnqueuedState
.QueueFilter
class will do two things:EnqueuedState
or the ScheduledQueueState
and grab their Queue
property to store as a custom job parameter, andQueue
job parameter when transitioning to (or electing) the EnqueuedState
.
using System;
using Hangfire.Client;
using Hangfire.States;
public sealed class QueueFilter : IClientFilter, IElectStateFilter
{
public const string QueueParameterName = "Queue";
public void OnCreated(CreatedContext filterContext)
{
}
public void OnCreating(CreatingContext filterContext)
{
string queue = null;
switch (filterContext.InitialState)
{
case EnqueuedState es:
queue = es.Queue;
break;
case ScheduledQueueState sqs:
queue = sqs.Queue;
break;
default:
break;
}
if (!string.IsNullOrWhiteSpace(queue))
{
filterContext.SetJobParameter(QueueFilter.QueueParameterName, queue);
}
}
public void OnStateElection(ElectStateContext context)
{
if (context.CandidateState.Name == EnqueuedState.StateName)
{
string queue = context.GetJobParameter<string>(QueueFilter.QueueParameterName)?.Trim();
if (string.IsNullOrWhiteSpace(queue))
{
queue = EnqueuedState.DefaultQueue;
}
context.CandidateState = new EnqueuedState(queue);
}
}
}
EnqueuedState
. If it is, we look for our previously set custom parameter and use it to create a new version of the EnqueuedState
to transition into instead.ScheduledQueueState
? First, we need to register our QueueFilter
into Hangfire’s processing pipeline:services.AddHangfire(configuration: (services, config) =>
{
config.UseFilter(new QueueFilter());
});
Schedule
overloads that we need. For example:public static string Schedule(
[NotNull] this IBackgroundJobClient client,
[NotNull, InstantHandle] Expression<Action> methodCall,
TimeSpan delay,
string queue)
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}
return client.Create(methodCall, new ScheduledQueueState(delay, queue));
}
Task
and don’t take a parameter onto the scheduled
queue as follows:// Acquire a reference to IBackgroundJobClient via dependency injection.
private IBackgroundJobClient client;
// When you want to schedule your job.
this.client.Schedule(
() => Console.Log("Hello, world!"),
TimeSpan.FromDays(1),
"scheduled");