Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I guarantee that only one JobInstance of a job run at the same time?

Tags:

spring-batch

Spring Batch documentation says: "Spring Batch will make no attempt to stop them from being run concurrently" (http://static.springsource.org/spring-batch/reference/html-single/index.html).

But I would like to get an error if I try to run a job and there is an instance of that job running. Is it possible?

I am using Spring Batch 2.1.8.

like image 655
Abel ANEIROS Avatar asked Mar 20 '12 13:03

Abel ANEIROS


2 Answers

If you're aware that subsequent job will be queued up, you can use TaskExecutor.

  1. Instantiate a task executor with maximum pool size, say 500

    <task:executor id="poolTaskExecutor" pool-size="500"/>
    
  2. ThrottledTaskexecutor

    ThrottledTaskExecutor will pass only given number of tasks at a time to above poolTaskExecutor. This class can be found below in spring github, or you can download maven artifact. https://github.com/SpringSource/spring-batch-admin/blob/master/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/util/ThrottledTaskExecutor.java

  3. Instantiate ThrottledTaskExecutor

    <bean id="throttledTaskExecutor" 
          class="org.springframework.batch.admin.util.ThrottledTaskExecutor">
      <property name="taskExecutor" ref="poolTaskExecutor" />
      <property name="throttleLimit" value="1"/>
    </bean>
    
  4. ThrottledJobLauncher

    <bean id="throttledJobLauncher"
            class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <property name="jobRepository" ref="jobRepository" />
        <property name="taskExecutor" ref="throttledTaskExecutor" />
    </bean>
    

All jobs launched using throttledJobLauncher above will be running only one instance at a time. This is more flexible that you can limit one or multiple jobs with given throttledLimit.

Actually above poolTaskExecutor definition and ThrottledTaskexecutor class is from spring-batch-admin. These are out-of-box feature. You just have to define ThrottledTaskExecutor with limit and include in the jobLauncher of your job.

like image 85
chanokim Avatar answered Sep 27 '22 21:09

chanokim


You could check

jobExecution.getStatus()

as described in

https://stackoverflow.com/a/8711857/1627688

like image 28
ahaaman Avatar answered Sep 27 '22 22:09

ahaaman