Reputation: 2634
Every time I deploy my application I remove all recurring jobs and re-add them like the following:
JobStorage.Current.GetConnection().GetRecurringJobs().ForEach(x => RecurringJob.RemoveIfExists(x.Id));
....
MyJobs.ForEach(x => RecurringJob.AddOrUpdate<....
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 and I'd like this code that removes the jobs and re-adds them to happen once per ‘environment’, not once per hangfire server so several servers are not competing and adding the same jobs over and over.
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 - is there anything built in to Hangfire?
Upvotes: 1
Views: 1270
Reputation: 195
Please have a look at Hangfire.RecurringJobCleanUpManager. It might give you an example of how to deal with rescheduling recurring jobs.
There is no magic under the hood. It basically fetches all current recurring jobs, removes those which are no more present in code as 'scheduled' (here in library: enforced) and then adds those which are in code but did not appear while fetching current recurring jobs.
This is as you can see close to what you have done, just nicely packed into few classes. There is no other way than this unless you want to manually tamper Hangfire's metadata to update assembly names, version etc.
I can't see problem tied to pararellism in this solution. This does happens once per server instance, but since one server instance altered the state and made it proper, next server instances will simply fetch the correct state and realize they don't need to do anything. This will effectively make it "once per environment".
Upvotes: 1