RegisterRecurringJobs
Registers the recurring job classes found in the scanned assemblies and the hosted service that hands their schedules to Hangfire when the host starts. A class is discovered when it implements IRecurringJob and carries RecurringJobAttribute, and the RecurringJobs section can then override what that attribute declares. Pair it with AddCustomHangfire, in either order, since neither reads what the other registered.
Usage
using AlmightyShogun.Hangfire.RecurringJobs;
using Microsoft.Extensions.DependencyInjection;
builder.Services
.AddCustomHangfire()
.RegisterRecurringJobs(builder.Configuration);using AlmightyShogun.Hangfire.RecurringJobs;
[RecurringJob("cleanup-expired-sessions", "0 */6 * * *")]
public sealed class CleanupExpiredSessionsJob : IRecurringJob
{
public Task RunAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}Startup validation
The attribute scan runs when the host starts rather than during registration. An empty or malformed cron expression, a time zone the machine does not recognise, two jobs sharing a job id, or an override naming a job id nothing declares throws InvalidOperationException naming what is wrong, which stops the application before any schedule reaches Hangfire. Overridden values are checked exactly like declared ones. A job with Enabled set to false is checked the same way and still claims its job id, so parking a job cannot hide a broken expression or a collision until someone enables it again.
Parameters
assemblies: Assembly[]
Assemblies scanned for recurring job classes. Use the overload without it to scan the calling assembly instead; an empty array registers the scheduler with nothing to schedule.
configuration: IConfiguration?
Read for a RecurringJobs section overriding what the attributes declare. Omit it when every environment schedules the same jobs the same way.
Default: null
Returns
TheIServiceCollection instance with recurring jobs and the startup scheduler registered.Type signature
public IServiceCollection RegisterRecurringJobs(
IConfiguration? configuration = null
);
public IServiceCollection RegisterRecurringJobs(
Assembly[] assemblies,
IConfiguration? configuration = null
);