Search code examples
javaspringspring-mvcbatch-processingspring-batch

Get running job instance status from Controller


Is there a way to get the running job(s) that I've started before in a Controller? Here I have the controller and the task executor configuration for the launcher:

@Controller
@RequestMapping(value = "/action/file")
public class ArquivoController {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    @Qualifier(value = "jobValidateFile")
    private Job jobValidateFile;

    @RequestMapping(value = "/validate", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> validate(@RequestParam Long fileId, Principal user) {

        Map<String, JobParameter> parameters = new HashMap<String, JobParameter>();
        parameters.put("fileId", new JobParameter(fileId));

        JobExecution execution = this.jobLauncher.run(this.jobValidateFile, new JobParameters(parameters));

        return new ResponseBuilder().toSuccessResponse();
    }

    @RequestMapping(value = "/status", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> seeStatus(@RequestParam Long fileId) {

        // Get the running job status here.

        return new ResponseBuilder().toSuccessResponse();
    }
}

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

As you can see, I put the launcher as an asynchronous task. What I'm trying to do, is to get the batch status little by little. For example, I'm going to make a javascript who will call the "seeStatus" method every minute.

Thanks.


Solution

  • You have a couple options:

    1. Implement your own query to load all running jobs. The JobRepository persists to a very simple database schema so writing your own DAO for this would be very straight forward.
    2. If you know all the names of the jobs you are concerned with, you could loop through them with the JobExplorer#findRunningJobExecutions(String jobName). This will only work, however, if you have the job names.

    I'd recommend option 1.

    You can read more about the JobExplorer here: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/explore/JobExplorer.html