I have a list of recurring jobs set up in Hangfire, all with an interval of 20 minutes.
They all call the same method, but with different parameters. e.g.
Job ID test_1 => MyTestMethod(1)
Job ID test_50 => MyTestMethod(50)
Job ID test_37 => MyTestMethod(37)
Sometimes, a job might take longer than its interval, i.e. longer than 20 minutes, and I want to make sure that job doesn't get run again whilst another instance of it is already running.
The DisableConcurrentExecutionAttribute
is not suitable here, because the method CAN be run concurrently, just not with the same parameter(s).
I attempted to have a static Dictionary<string, DateTime>
that tracked whether a job was already running so that it could block concurrent method calls, but the problem there is that if the application restarts for any reason, then it "forgets" what jobs are currently running (Hangfire of course will continue to run in background).
UPDATE
I also tried adding a JobState table to my database to track which jobs are running and then checking that table when MyTestMethod starts, but this relies on MyTestMethod setting running=1 when it starts and running=0 when it ends and if the thread crashes halfway through that job (for whatever reason) that might not happen, thus preventing the job running again at all.
I am sure I can solve this by simply querying Hangfire job status by job ID - I just can't find how to do this?