11

Is it possible to get a list of defined jobs in Spring Batch at runtime without using db? Maybe it's possible to get this metadata from jobRepository bean or some similar object?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Vladyslav Sheruda
  • 1,856
  • 18
  • 26

4 Answers4

5

It is possible to retrieve the list of all job names using JobExplorer.getJobNames().

You first have to define the jobExplorer bean using JobExplorerFactoryBean:

<bean id="jobExplorer" class="org.springframework.batch.core.explore.support.JobExplorerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
</bean>

and then you can inject this bean when you need it.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
2

I use these code to list and execute jobs

private String jobName = "";
    private JobLauncher jobLauncher = null;
    private String selectedJob;
    private String statusJob = "Exit Status : ";
    private Job job;
    ApplicationContext context;
    private String[] lstJobs;

    /**
     * Execute
     */
    public ExecuteJobBean() {
        this.context = ApplicationContextProvider.getApplicationContext();
        this.lstJobs = context.getBeanNamesForType(Job.class);


        if (jobLauncher == null)
            jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    }

    /**
     * Execute
     */
    public void executeJob() {

        setJob((Job) context.getBean(this.selectedJob));

        try {
            statusJob = "Exit Status : ";
            JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();
            JobExecution execution = jobLauncher.run(getJob(), jobParameters);
            this.statusJob = execution.getStatus() + ", ";
        } catch (Exception e) {
            e.printStackTrace();
            this.statusJob = "Error, " + e.getMessage();
        }
        this.statusJob += " Done!!";
    }
ZaoTaoBao
  • 2,567
  • 2
  • 20
  • 28
2

To list jobs defined as beans, you can just let the spring context inject them for you all the bean types of type Job into a list as below:

@Autowired
private List<? extends Job> jobs;

..
//You can then launch you job given a name.
kosgeinsky
  • 508
  • 3
  • 21
  • Works for me, the @Autowired ListableJobLocator jobLocator; jobLocator.getJobNames(); suggestion from another answer did not return any job in my case. – nn4l Mar 03 '20 at 11:13
1

Alternative strategy to get list of job names that are configured as beans one can use the ListableJobLocator.

@Autowired
ListableJobLocator jobLocator;

....

jobLocator.getJobNames();

This does not require a job repository.

anojan
  • 43
  • 1
  • 5