How to ensure jobs scheduled once in web farm

Every time I deploy my application I remove all recurring jobs and reschedule them.
I need to do this to get around activation issues where I change the version number of my assemblies with each deployment and after deploying “MyAssembly, 2.0.0.0”, the original records with “MyAssembly, 1.0.0.0” not longer activate correctly, so after every release (actually every App Pool restart), I remove the recurring jobs and reschedule them. All is well and good.

I’m looking to start running my jobs in a web farm though and I just want my jobs scheduled once per ‘environment’, not once per hangfire server.

I could probably designate one instance as the ‘leader’ via a web.config setting and only the leader would perform the scheduling of jobs, but what if my ‘leader’ didn’t come online after a deployment. I’d also like all my config files to be identical and not to have to configure one as a ‘leader’ in my CD pipiline.

What’s the best way to handle this scenario?

There’s not way I can think of without involving an external system while still remaining robust enough to deal with the scenario you mentioned.

You could:

  • expose an endpoint that does the scheduling work and then call it as a part of your CD pipeline
  • put the scheduling code inside a Background Job and queue it up manually or as part of your CD pipeline
  • store some state in a shared resource (i.e. db) and run the Background Job on start up, checking that shared state before doing the scheduling work. You’d probably need to capture the assembly version at the very least, for comparison against current assembly version. This is probably the most complicated option due to timing/contention.

Please Use the Windows service.