Pages

Sunday, September 26, 2010

Stateful Quartz job

Quartz job does a good job for scheduling.We have a quartz job for processing a file which is scheduled to run every 5 minutes. Recently we came across a problem. Normally the file processing will take only less than the trigger interval so there will be only one job running at any point of time. Due large file size, the file processing time started taking more than 5 minute, which means a second job will be triggered before the first one finished. The second one will grab the same file again and will crate so many issues like duplicate entries, file permission issues etc etc.
We started thinking about "Only one should run at any point of time" requirement. Luckily there is a simple and smart way to achieve this. Declare the job as "Stateful".

if a job is stateful, and a trigger attempts to 'fire' the job while it is already executing, the trigger will block (wait) until the previous execution completes.

You 'mark' a Job as stateful by having it implement the StatefulJob interface, rather than the Job interface.


  public class sampleJob
                     extends QuartzJobBean
                       implements StatefulJob
    {

         protected void executeInternal(final JobExecutionContext _ctx)
                                                           throws JobExecutionException
   {
    // Do the job here
    }
  }
Related Posts Plugin for WordPress, Blogger...