Reputation: 71
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.
Upvotes: 4
Views: 6949
Reputation: 51
a stupid but work solution would be put the content of the logic in another function and call the schedule in 2 different function with different schedule setting
@Scheduled(cron = "0 10 19 * * FRI", zone = "CET")
public void scheduleCetTask() {
// code to get parameters
commonTask(parameters);
}
@Scheduled(cron = "0 10 19 * * FRI", zone = "ABC")
public void scheduleAbcTask() {
// code to get parameters
commonTask(parameters);
}
public void commonTask(parameters) {
}
Upvotes: 0
Reputation: 12999
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.
Upvotes: 2
Reputation: 1058
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
Upvotes: 1
Reputation: 1121
Use zone property with annotation @Scheduled, (version 4.0 addition) See Example below
@Scheduled(cron = "0 10 19 * * FRI", zone = "CET")
Upvotes: 3