How to Schedule a job in Java using Spring Boot Scheduler?

javatechonline blog
2 min readJun 23, 2022

Now-a-days, most of the applications come across a requirement where scheduling a task/job becomes mandatory. In other words, almost every client expects this functionality to be implemented in the project. Hence, as a developer it becomes important to learn scheduling concept especially using Spring Boot.

For example, generating a report in a particular time interval is possible by implementing the scheduling concept. Furthermore, the places where we can use scheduling are Salary Slip generation, Insurance Payment, Monthly Bank Statements, Daily Stand up meetings in Offices, Electricity Bill, Sprint Planning etc.

Cron Expressions in Spring Boot Scheduler

What are the steps to implement Scheduling in Spring Boot ?

Step#1 : Create Spring Boot Starter Project using STS(Spring Tool Suite) : No need to add any other starter dependency.

Step#2 : At Starter class apply @EnableScheduling

Step#3 : Additionally, define a class and apply @Component over the class

Step#4 : Finally, Implement a method in above class accordingly, which executes the task and apply @Scheduled(……………)

Why we use @Scheduled Annotation?

This annotation instructs Spring Container to execute the method in a loop as per the provided parameters until the application/server stops. However, it uses below concepts to support scheduling.
1) fixed Delay
2) fixed Rate
3) cron expression

Note: We can’t write @Scheduled without any input in the bracket, other wise Spring container will throw IllegalStateException: Encountered invalid @Scheduled method ‘generateReport’: Exactly one of the ‘cron’, ‘fixedDelay(String)’, or ‘fixedRate(String)’ attributes is required.

Examples of a Scheduled Task using cron expressions in Spring Boot Scheduler

Write a cron expression that executes a task everyday at 4 PM

0   0   16   *   *   *

Write a cron expression that executes a task at 8AM, 9AM, 10AM and 11AM every day

0   0   8-11   *   *   *

Write a cron expression that executes a task 4 times each after one hour, first at 9PM everyday

0   0   21-00   *   *   *      OR    0   0   21,22,23,00   *   *   *

Write a cron expression that executes a task every year on Feb 14th 9:00:00 AM if given day(14th) is Sunday or Tuesday only.

0   0   9   14   2   SUN,TUE

If you are further looking for the complete tutorial on Spring Boot Scheduler with various examples especially using cron expressions, you may visit ‘How to implement Spring Boot Scheduler to schedule a task?’ You will have a clear idea on this after practicing multiple examples given in th article.

--

--