Cancellation Token
Using Cancellation Tokens — Hangfire Documentation
Hangfire provides support for cancellation tokens for our background jobs to let them know when a shutdown request was initiated, or job performance was aborted. In the former case the job will be automatically put back to the beginning of its queue, allowing Hangfire to process it after restart.
https://docs.hangfire.io/en/latest/background-methods/using-cancellation-tokens.html
Given a cancellation request is make, the task will end and be scheduled for re-execution, this is something you must consider, to ensure non-duplicate scenarios.
Queueing a Task
BackgroundJob.Enqueue<IService>(x => x.LongRunningMethod(CancellationToken.None));
Task
public async Task LongRunningMethod(CancellationToken token)
{
for (var i = 0; i < Int32.MaxValue; i++)
{
await Task.Delay(TimeSpan.FromSeconds(1), token);
}
}
Cancellation Polling Interval Options
services.AddHangfireServer(new BackgroundJobServerOptions
{
CancellationCheckInterval = TimeSpan.FromSeconds(5) // Default value
});