Ask Your Question
3

How can a Spring Batch Job be scheduled to run automatically when the application starts up?

asked 2023-05-06 11:12:43 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-06 11:28:01 +0000

scrum gravatar image

To schedule a Spring Batch job to run automatically when the application starts up, you can use the @Scheduled annotation on a method in a @Configuration class.

  1. First, annotate the configuration class with @EnableScheduling so that Spring knows to look for scheduled tasks.

  2. Then, create a method in the configuration class and annotate it with @Scheduled to indicate that it should be run according to a fixed schedule.

  3. Inside the method, use the JobLauncher to launch the Spring Batch job.

Here is an example:

@Configuration
@EnableScheduling
public class BatchConfig {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job myJob;

    @Scheduled(fixedDelay = 1000) // run every second
    public void runJob() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        jobLauncher.run(myJob, new JobParameters());
    }
}

In this example, the runJob() method will be automatically executed every second due to @Scheduled(fixedDelay = 1000). Inside the method, the JobLauncher launches the myJob Spring Batch job with an empty JobParameters object.

Note: If you don't want your job to be executed repeatedly, you can change fixedDelay to something like fixedRate or use a Cron expression to schedule your job according to your needs.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-06 11:12:43 +0000

Seen: 9 times

Last updated: May 06 '23