Rescheduling Hangfire Jobs using appSettings.json

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:

  1. Remove the job from the code, recompile and redeploy.
  2. Using Hangfire Dashboard and delete the job.
    However, the job may get added back in when the app pool recycle.

Hangfire.Rescheduler

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: