This article explains how to configure Schedule with time zone. Scheduling a task with Spring Boot with time zone is as simple as annotating a method with @Scheduled annotation, and giving cron expression as a parameter and zone as an another parameter. This cron expression is used to determine when the task is going to run on specified time zone.

There are two ways to configure the time zone in spring boot. Scheduler time zone is configured using the name of the time zone and GMT time.



Using Time Zone Name

There is a zone element in the @scheduled annotation used to configure the time zone for the cron job. The time zone can be added as a string which can be accepted by Java.util. TimeZone. This zone element is available from version 4.0. 

The example below shows how to configure a scheduler with time zone name.

package com.yawintutor;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerZone {
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
   
   @Scheduled(cron = "0/5 * * ? * *", zone="IST")
   public void task() {
      System.out.println("Scheduler (zone = IST) task with duration : " + sdf.format(new Date()));
   }
}


Console Output

The console output of the above program is shown in the following

Scheduler (zone = IST) task with duration : 2019-12-03 22:43:30.003
Scheduler (zone = IST) task with duration : 2019-12-03 22:43:35.005
Scheduler (zone = IST) task with duration : 2019-12-03 22:43:40.007
Scheduler (zone = IST) task with duration : 2019-12-03 22:43:45.005
Scheduler (zone = IST) task with duration : 2019-12-03 22:43:50.005


Using GMT Time

In the Spring boot, GMT time can be used to configure Scheduler using cron job with time zone. GMT is a common time standard that is practiced to translate the time around the globe. The time of GMT ranges from GMT-12 to GMT+12.

The example below shows how to configure GMT time in the @scheduled annotation zone element.

package com.yawintutor;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerZone {
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
   
   @Scheduled(cron = "0/5 * * ? * *", zone="GMT+5.30")
   public void task() {
      System.out.println("Scheduler (zone=\"GMT+5.30\") task with duration : " + sdf.format(new Date()));
   }
}


Console Output

The console output of the above program is shown in the following

Scheduler (zone="GMT+5.30") task with duration : 2019-12-03 22:39:45.001
Scheduler (zone="GMT+5.30") task with duration : 2019-12-03 22:39:50.001
Scheduler (zone="GMT+5.30") task with duration : 2019-12-03 22:39:55.008


Leave a Reply