0

Spring wonderfully offers a zone attribute to the @Scheduled annotation. I am looking to provide the @Scheduled method with a time zone programmatically.

For example, say I want to turn the lights on at buildings in LA and Chicago, both at midnight local time. I want to get the buildings from my repository.

Can the time zone be provided at runtime or otherwise injected?

Like:

@Scheduled(cron = "0 0 * * * *", zone = {THE_ZONE}) //midnight
public void myScheduledMethod() {       
     //...      
     building.toggleLights();  //could be LA or Chicago
}

I know that the @Scheduled method can't take any arguments, so providing the time zone that way won't do it.

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80

1 Answers1

0

Just use a value expression.

@Scheduled(cron = "0 0 * * * *", zone = "${zone.property}") //midnight
public void myScheduledMethod() { ... }

This will use the Environment to lookup the property named zone.property which can be set as en environment variable, read from a properties file etc.

If you want to retrieve them, as you state from the db, you would have to manually schedule the methods and not use the @Schedule method. Create a bean that at startup reads from the DB and registers the tasks with a TaskScheduler.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • Exactly, so I'd need to go the bean route and not use the simpler `@Scheduled` way. Imagine you have hundreds of buildings in hundreds of cities... – riddle_me_this Jun 22 '17 at 14:49
  • That would be a single factory reading the schedules from a database and schedule them. Just create the beans based on the database information. – M. Deinum Jun 22 '17 at 17:55