The @Scheduled annotation in Spring allows you to use Spring Expression Language (SpEL) to define dynamic cron expressions, fixed rates, and delays.
package com.logicbig.example; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalTime; @Component public class MyBean { @Scheduled( fixedDelayString = "#{T(com.logicbig.example.ScheduledExample).getTaskRate()}") public void runTask() { System.out.printf("Running scheduled task " + " thread: %s, time: %s%n", Thread.currentThread().getName(), LocalTime.now()); } }
package com.logicbig.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import java.util.TimeZone; @ComponentScan @EnableScheduling @Configuration public class ScheduledExample { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ScheduledExample.class); } public static String getTaskRate(){ TimeZone tz = TimeZone.getDefault(); if(tz.getID().equals("America/New_York")){ return "1000"; }else{ return "3000"; } } }
Running scheduled task thread: pool-1-thread-1, time: 16:08:41.937174200Running scheduled task thread: pool-1-thread-1, time: 16:08:44.944081800Running scheduled task thread: pool-1-thread-1, time: 16:08:47.950042600Running scheduled task thread: pool-1-thread-1, time: 16:08:50.956851800......................
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.