Spring Batch Scheduler with Spring Boot Example, easy in 10 minutes

Today, I show you how to create a Spring Batch Scheduler with Spring Boot Example. This post introduces very clear to help you understand job scheduling with Spring Boot. Moreover, we also mention the cron expression and some cron patterns then you can declare your own cron pattern by yourself. Let’s dive into

Spring Batch Scheduler with Spring Boot Example

Project Setup

Tools and framework that we use:
Spring Boot 2.2.2 RELEASE
Spring Batch 4.2.1
Maven 3.6
Java 8

Project Directory

Our project will have a structure like below

Spring Batch Scheduler with Spring Boot Example

Project Dependencies

We’re using the dependencies like below

Cron expression

Cron expression is represented by six fields:

Or you may refer to the graphically cron expression below:

cron expression

From the above cron expression, we give you some example patterns:

Configure batch job scheduler with spring boot

Configuring batch job scheduler very easy with spring boot, we just do two steps:

  1. Enable scheduling with @EnableScheduling annotation.
  2. Create a method annotated with @Scheduled and a cron job pattern.

Here is the detail implementation of the above steps in MySpringBootApplication class

Dig deeper: Above, we implement the job scheduler with cron patternĀ */10 * * * * *? . That means it runs every ten seconds.

DEMO

To show you how Spring batch job scheduler works, we reuse the source code from the post Spring Batch Hello World Example with Spring Boot

. Certainly, we must implement a bit additional java code for job scheduler processing. You just update the MySpringBootApplication class like above. It’s quite easy, isn’t it?

To demo our Spring Batch Scheduler with Spring Boot Example, we run the below command in the console.

Note: You must be in your project directory before run that command.
While running that command, you will see the output like below

Spring Batch Scheduler with Spring Boot Example

Let’s have a look at the screenshot, our program is reading employee information from CSV file. Every ten minutes, it repeats reading again. So this program works like what we want, congratulation!

If you’re not sure about the implementation, you can download the complete source code of Spring Batch Scheduler with Spring Boot Example at the bottom of this post. That’s all about Spring Batch Scheduler with Spring Boot Example.

If you find this post useful, don't hesitate to share it with your friends or other people for growing knowledge together and is an effort to contribute us.

References

Spring Boot Tutorial for Beginners
Spring Batch Frameworks
Spring Scheduling
Spring cron expression

Download the complete source code

SpringBatch-Job-Scheduler-Example.zip (32 downloads)
Please share it if you found this useful
Hide Buttons