menu

Spring Boot - Schedular

Scheduling is a process of executing the tasks for the specific time period. Spring Boot provides a good support to write a scheduler on the Spring applications.

The two annotations which are used to define a scheduler in spring boot application.

The @EnableScheduling annotation is used to enable the scheduler for your application.

The @Scheduled annotation is used to trigger the scheduler for a specific time period.

Types Of Schedulars

Fixed Delay

Fixed Delay scheduler is used to execute the tasks at a specific time. It wait for the previous task completion. The values should be in milliseconds. A sample code is shown here

Fixed Rate

Fixed Rate scheduler is used to execute the tasks at the specific time. It does not wait for the completion of previous task. The values should be in milliseconds.

This option should be used when each execution of the task is independent.

The sample code is shown here

A sample code for executing a task on every second from the application startup, but it would not worked as aspected.

Because scheduled tasks don't run in parallel by default. So even if we used fixedRate, the next task won't be invoked until the previous one is completed.

If we want to support parallel behavior in scheduled tasks, we need to add the @EnableAsync and @Async annotations:

The sample code using @EnableAsync and @Async annotations is shown here

Initial Delay

The initialDelay is the time after which the task will be executed the first time after the initial delay value.

Java Cron Expression

Cron expressions are used to configure instances of CronTrigger, a subclass of org.quartz.Trigger. A cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule.

These fields, separated by white space, can contain any of the allowed values with various combinations of the allowed characters for that field.

Table: Cron Expressions Allowed Fields and Values in the expected order.

image not found

Example: Cron Expressions

Cron expressions can be as simple as * * * * ? * or as complex as 0 0/5 14,18,3-39,52 ? JAN,MAR,SEP MON-FRI 2002-2010.

image not found