Hangfire is a powerful tool to schedule a background job. With its simple-to-use API, one can easily register a background job using a couple of lines of code.
RecurringJob.AddOrUpdate<DirectoryCleaner>("DirectoryCleaner", job => job.Cleanup(), Cron.Daily);
RecurringJob.AddOrUpdate<CacheCleaner>("CacheCleaner", job => job.CleanCache(), Cron.Daily);
This code tells Hangfire to create two background jobs to run on everyday at midnight: “DirectoryCleaner” and “CacheCleaner”.
However, there are some drawbacks with this approach. If there’s a need to disable or to modify the occurrence of these jobs, you have 2 options:
- Remove the job from the code, recompile and redeploy.
- Using Hangfire Dashboard and delete the job.
However, the job may get added back in when the app pool recycle.
So, I created Hangfire.Rescheduler
to allow more flexibility around job scheduling. Consider the following approach:
appSettings.json
{
"jobOptions": {
"schedules": [{
"jobId": "CacheCleaner",
"isEnabled": false,
"cron": "0 1 * * *"
},{
"jobId": "DirectoryCleaner",
"isEnabled": true,
"cron": "0 1 * * *",
"timezoneId": "UTC"
},
]
}
}
Program.cs
...
RecurringJob.AddOrUpdate<DirectoryCleaner>("DirectoryCleaner", job => job.Cleanup(), Cron.Daily);
RecurringJob.AddOrUpdate<CacheCleaner>("CacheCleaner", job => job.CleanCache(), Cron.Daily);
IServiceProvider services = ...
IConfigurationRoot root = ...
var options = root.getConfiguration<JobReschedulingOption>("JobOptions");
var jobRescheduler = services.GetService<IJobRescheduler>();
jobRescheduler.LoadSchedules(options);
...
IJobRescheduler
allows you to modify your Hangfire jobs using appSettings.json (or other ways using JobReschedulingOption
) . It provides a way to turn on/off, reschedule (using Cron expression) a job by its id
.
This library is really simple to implement check out the code on github: https://github.com/bingzer/Hangfire.Rescheduler