membersound
membersound

Reputation: 86637

How to launch a Spring Batch job after startup?

How can I run a job configured using Spring-Batch right after application startup?

Currently I'm specifying an exact time using cron job, but that requires to change the cron every time I restart the application:

@JobRegistry, @Joblauncher and a Job. I execute the job as follows:

@Scheduled(cron = "${my.cron}")
public void launch() {
    launcher.run(job, params);
}

Upvotes: 1

Views: 2934

Answers (2)

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18383

Checking aroud Spring code I have found SmartLifecycle

An extension of the Lifecycle interface for those objects that require to be started upon ApplicationContext refresh and/or shutdown in a particular order. The isAutoStartup() return value indicates whether this object should be started at the time of a context refresh.

Try creating a custom bean implementing SmartLifecycle and setting autoStartup; when this custom bean start method is invoked launch your job.

Upvotes: 2

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

A few options that I can think of on the places to put your startup logic:

.1. In a bean @PostConstruct annotated method, reference is here - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-postconstruct-and-predestroy-annotations

.2. By implementing an ApplicationListener, specifically for either ContextStartedEvent or ContextRefreshedEvent. Reference here - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#context-functionality-events

Upvotes: 1

Related Questions