user1052610
user1052610

Reputation: 4719

How to continually run a Spring Batch job

What is the best way to continually run a Spring Batch job? Do we need to write a shell file which loops and starts the job at predefined intervals? Or is there a way within Spring Batch itself to configure a job so that it repeats at either

1) pre-defined intervals

2) after the completion of each run

Thanks

Upvotes: 3

Views: 6018

Answers (3)

EliuX
EliuX

Reputation: 12625

Id did something like this for importing emails, so i have to check it periodically

@SpringBootApplication
@EnableScheduling
public class ImportBillingFromEmailBatchRunner
{
    private static final Logger LOG = LoggerFactory.getLogger(ImportBillingFromEmailBatchRunner.class);

    public static void main(String[] args)
    {
        SpringApplication app = new SpringApplication(ImportBillingFromEmailBatchRunner.class);
        app.run(args);
    }

    @Bean
    BillingEmailCronService billingEmailCronService()
    {
        return new BillingEmailCronService();
    }

}

So the BillingEmailCronService takes care of the continuation:

public class BillingEmailCronService
{
    private static final Logger LOG = LoggerFactory.getLogger(BillingEmailCronService.class);

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private JobExplorer jobExplorer;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private @Qualifier(BillingBatchConfig.QUALIFIER)
    Step fetchBillingFromEmailsStep;

    @Scheduled(fixedDelay = 5000)
    public void run()
    {
       LOG.info("Procesando correos con facturas...");
       try
       {
          Job job = createNewJob();
          JobParameters jobParameters = new JobParameters();
          jobLauncher.run(job, jobParameters);
       }catch(...)
       {
          //Handle each exception
       }
    }
}

Implement your createNewJob logic and try it out.

Upvotes: 1

Oussama Zoghlami
Oussama Zoghlami

Reputation: 1708

If you want to launch your jobs periodically, you can combine Spring Scheduler and Spring Batch. Here is a concrete example : Spring Scheduler + Batch Example.

If you want to re-launch your job continually (Are you sure !), You can configure a Job Listener on your job. Then, through the method jobListener.afterJob(JobExecution jobExecution) you can relaunch your job.

Upvotes: 3

Vinay Lodha
Vinay Lodha

Reputation: 2223

one easy way would be configure cron job from Unix which will run application at specified interval

Upvotes: 0

Related Questions