Spring Boot: CRON Scheduler Jobs

{getToc} $title={Table of Contents}

Cron Jobs Scheduler

Introduction

In this blog, I'm going to write about my best practise on Cron Jobs using @Scheduled Annotation (Annotation is used for task scheduling) in Spring. The trigger information needs to be provided along with this annotation.

Spring Boot provides a very simple way of setting up Cron jobs in an application using Spring Scheduler. Scheduling is the process of executing a piece of logic at a specific time in the future. Scheduled jobs are a piece of business logic that should run on a timer. Spring allows us to run scheduled jobs in the Spring container by using some simple annotations.

Enabling Scheduling

Scheduling is not enabled by default. Before adding any scheduled jobs we need to enable scheduling explicitly by adding the @enableScheduling annotation:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableAsync
@EnableScheduling
public class BackEndApp {
	public static void main(String[] args) {
		SpringApplication.run(BackEndApp.class, args);
	}

}


@enableScheduling with this annotation, we can enable scheduling in the application.
- @EnableAsync with this annotation, we can enable asynchronous functionality in Spring.

The scheduling will now only be activated when we load the SchedulerConfig class into the application, providing better modularization.

When the @EnableScheduling annotation is processed, Spring scans the application packages to find all the Spring Beans decorated with @Scheduled methods and sets up their execution schedule.


Adding Scheduled Jobs

After enabling scheduling, we will add jobs to our application for scheduling. We can turn any method in a Spring bean for scheduling by adding the @Scheduled annotation to it.

The @Scheduled is a method-level annotation applied at runtime to mark the method to be scheduled. It takes one attribute from cron, fixedDelay, or fixedRate for specifying the schedule of execution in different formats.

The annotated method needs to fulfill two conditions:

  1. The method should not have a return type and so return void. For methods that have a return type, the returned value is ignored when invoked through the scheduler.
  2. The method should not accept any input parameters.

fixedDelay 

We use the fixedDelay attribute to configure a job to run after a fixed delay which means the interval between the end of the previous job and the beginning of the new job is fixed.

The new job will always wait for the previous job to finish. It should be used in situations where method invocations need to happen in a sequence.

@Scheduled(fixedDelay =30000)
public void croServiceMethod () {... }

Here we have scheduled the execution of the cron method with a fixed delay by setting the fixedDelay attribute to 30000 milliseconds or 30 seconds.

fixedRate 

We use the fixedRate attribute to specify the interval for executing a job at a fixed interval of time. It should be used in situations where method invocations are independent. The execution time of the method is not taken into consideration when deciding when to start the next job.

@Scheduled(fixedRate=30000)
public void cronServiceMethod () {... }

Here we have scheduled the execution of the cron method with a fixed rate by setting the fixedRate attribute to 30000 milliseconds or 30 seconds.


@Scheduled with cron expression

We'll implement by using Using Cron Expressions to Define the Interval in more detail. Sometimes delays and rates are not enough, and we need the flexibility of a cron expression to control the schedule of our tasks.


In this method, cron attribute is used with @Scheduled annotation. Value of this attribute must be a cron expression.

Here we have specified the interval using a cron expression externalized to a property named cron-push-notification defined in our application.properties file.

cron.push.notification=0 0 07 * * ?

You can annotate on your cron service like this:

@Scheduled(cron = "${cron.push.notification}")
public void croServiceMethodPushNoti() throws Exception {
try { logger.info("====== START CRON PUSH NOTIFICATION ======="); } catch (Exception e) { e.printStackTrace(); throw e; } }

This will auto run push notification service cron at 7:00 a.m everyday.


A cron expression is a string of six to seven fields separated by white space to represent triggers on the second, minute, hour, day of the month, month, day of the week, and optionally the year. However, the cron expression in Spring Scheduler is comprised of six fields as shown below:

 ┌───────────── second (0-59)
 │ ┌───────────── minute (0 - 59)
 │ │ ┌───────────── hour (0 - 23)
 │ │ │ ┌───────────── day of the month (1 - 31)
 │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
 │ │ │ │ │ ┌───────────── day of the week (0 - 7)
 │ │ │ │ │ │          (or MON-SUN -- 0 or 7 is Sunday)
 │ │ │ │ │ │
 * * * * * *

For example, a cron expression: 0 30 15 * * * is triggered to run at 3:30 p.m. every day ( every 0th second, 30th minute, 3th hour, every day). 

* indicates the cron expression matches for all values of the field. 
For example, * in the minute field means every minute.

Here we have specified an hourly interval with a cron macro: hourly instead of the less readable cron expression 0 0 * * * *.

@Scheduled(cron = "0 0 * * * *") ➜ @Scheduled(cron = "@hourly")

Spring provides the following macros:

  • @hourly,
  • @yearly,
  • @monthly,
  • @weekly, and
  • @daily


Conclusion

Here is a list of major points from the tutorial for quick reference:

  • Scheduling is part of the core module, so we do not need to add any dependencies.
  • Scheduling is not enabled by default. We explicitly enable scheduling by adding the @EnableScheduling annotation to a Spring configuration class or Main application class.
  • We can make the scheduling conditional on a property so that we can enable and disable scheduling by setting the property.
  • We create scheduled jobs by decorating a method with the @Scheduled annotation.
  • Only methods with void return type and zero parameters can be converted into scheduled jobs by adding @Scheduled annotation.
  • We set the interval of executing by specifying the fixedRate or fixedDelay attribute in the @Scheduled annotation.
  • We can choose to delay the first execution of the method by specifying the interval using the initialDelay attribute.


Previous Post Next Post