Mutexes
Mutexes in JobRunr will postpone jobs until a shared mutex is free
A mutex
is a mutually exclusive flag. It acts as a gate keeper to a resource allowing only one Job
to use it and postpones all others jobs using the same mutex
.
You cannot use both a mutex and a rate limiter on the same
Job
.
Usage via @Job
annotation
Using a mutex is as easy as using Queues and Server Tags, again thanks to the Job
annotation. Just add it to your service method and specify the mutex to use
@Job(mutex = "virus-scanner")
public void onlyProcessOneJobAtTheSameTime() {
System.out.println("This will not run parallel as it is guarded by a mutex");
}
Usage via JobBuilder
pattern
When you are using the JobBuilder
pattern, you can pass the serverTag via the JobBuilder
.
jobScheduler.create(aJob()
.withMutex("virus-scanner")
.withDetails(() -> System.out.println("This will not run parallel as it is guarded by a mutex"));
Advanced example Mutexes can also take into account job parameters. In the example below, we have 3 mutexes in total:
virus-scanner/LINUX
virus-scanner/WINDOWS
virus-scanner/MACOS
public void scanForViruses(File folder) {
for(String f : folder.list()) {
scanForViruses(f);
}
}
public void scanForViruses(String file) {
BackgroundJob.enqueue(() -> osSpecificVirusScan("LINUX", file));
BackgroundJob.enqueue(() -> osSpecificVirusScan("WINDOWS", file));
BackgroundJob.enqueue(() -> osSpecificVirusScan("MACOS", file));
}
@Job(mutex = "virus-scanner/%0")
public void osSpecificVirusScan(String os, String file) {
System.out.println(String.format("This will result in a mutex virus-scanner/%0", os));
}
Configuration
Mutexes don’t require any configuration.