简体   繁体   中英

Spring @Scheduled task in multiple timezones

I have a client that operates across the US (in all time zones). I need to run a task at 2AM in each time zone. This task needs time zone as input to fetch records only related that zone.

@Scheduled annotation has timezone value, that works of one timezone at a time.

I do not want to duplicate the code by having 4 separate tasks for each zone.

使用带注释@Scheduled的zone属性(版本4.0添加)请参阅下面的示例

@Scheduled(cron = "0 10 19 * * FRI", zone = "CET") 

Can you try this approach ? As per java 8 repeatable annotations docs it should work,@Repeatable is already included in @Scheduled, so no need to declare @scheduled again with @Repeatable annotation

org.springframework.scheduling.annotation.Scheduled

@Repeatable(value=Schedules.class) @Target(value={ANNOTATION_TYPE, METHOD}) @Retention(value=RUNTIME) @Documented

   @Scheduled(cron = "0 1 1,13 * * ?", zone = "CST")
    @Scheduled(cron = "0 1 1,15 * * ?", zone = "SGT")
    public void doScheduledWork() {
        //complete scheduled work
    }
.
.
.

related docs/links : java-8 repeatable custom annotations https://www.javatpoint.com/java-8-type-annotations-and-repeating-annotations

This should do it for you.

@Slf4j
@Configuration
public class TestBean implements SmartInitializingSingleton {

  @Inject
  TaskScheduler scheduler;

  @Bean
  public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler te = new ThreadPoolTaskScheduler();
    te.setPoolSize(4);
    return te;
  }

  @Override
  public void afterSingletonsInstantiated() {

    Arrays.stream(new String[] {"PST", "MST", "CST", "EST"})
        .forEach(zone -> {
          scheduler.schedule(() -> {
            log.info("Zone trigged: {}", zone);
          }, new CronTrigger("0 0 2 * * *", TimeZone.getTimeZone(zone)));
        });
  }
}

You may want to separate out the different concerns of creating the scheduler bean and the task execution. Also, take care to choose a suitable scheduler that has the parallelism you need in the event that a job runs over into the trigger time of the next job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM