Hangfire running recurring jobs on different web servers

Viewed 524

We have multiple web servers running our sites, with load balancers, so users are directed to different servers depending on the load. The code is the same for each instance on each server, and we have recurring jobs that are run. Obviously we dont want the jobs to run at the same time on both servers.

Does hangfire implement a lock when a job is run so it is not run again automatically?

Currently we have this already on each method that is run [Hangfire.DisableConcurrentExecution(60 * 60 * 5)] will that stop both servers running the code at the same time?

1 Answers

Take a look on Mutexes. They will prevent the execution two processes in the same time which need access to one resource.

Mutex prevents concurrent execution of multiple background jobs that share the same resource identifier. Unlike other primitives, they are created dynamically so we don’t need to use IThrottlingManager to create them first. All we need is to decorate our background job methods with the MutexAttribute filter and define what resource identifier should be used.

[Mutex("my-resource")]
public void MyMethod()
{
    // ...
}

When we create multiple background jobs based on this method, they will be executed one after another on a best-effort basis with the limitations described below. If there’s a background job protected by a mutex currently executing, other executions will be throttled (rescheduled by default a minute later), allowing a worker to process other jobs without waiting.

Source: https://docs.hangfire.io/en/latest/background-processing/throttling.html#

Related