Prevent Scheduler job contention
Last modified by Clemens Robbenhaar on 2021/03/18 11:28
![]() | Prevents the same scheduler job from running twice at the same time |
Type | Snippet |
Category | |
Developed by | |
Rating | |
License | GNU Lesser General Public License 2.1 |
Table of contents
Description
It can happen that a job is triggered before the last execution of that job is over. Some issues may appear, because the 2 instances of the job share the same xwiki context. It can break the Database session and then the xwiki has to be restarted.
Code
To avoid that, you can use the following code in your scheduler job:
if(xcontext.get("JOB_LOCK") != "locked"){
try{
// Lock
xcontext.put("JOB_LOCK", "locked");
// Script
// Your script here
// ...
}catch(Exception e){
System.out.println("JOB {description of your job here} EXCEPTION:");
e.printStackTrace();
}finally{
xcontext.put("JOB_LOCK", "free");
}
}else{
System.out.println("JOB {description of your job here} IMPOSSIBLE BECAUSE THE LAST JOB IS STILL RUNNING ("+new Date()+").");
}
try{
// Lock
xcontext.put("JOB_LOCK", "locked");
// Script
// Your script here
// ...
}catch(Exception e){
System.out.println("JOB {description of your job here} EXCEPTION:");
e.printStackTrace();
}finally{
xcontext.put("JOB_LOCK", "free");
}
}else{
System.out.println("JOB {description of your job here} IMPOSSIBLE BECAUSE THE LAST JOB IS STILL RUNNING ("+new Date()+").");
}
Explanation
A lock is stored in the context. Since 2 instances of the same job have the same context, we can avoid the script to be run if the lock is not free.