Spring @Scheduled annotation

Chandz picture Chandz · Jul 27, 2015 · Viewed 16.8k times · Source

How can I use @Scheduled annotation of spring dynamically?

CronTrigger(String expression, TimeZone timeZone)

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronTrigger.html#CronTrigger-java.lang.String-java.util.TimeZone-

As I have multiple timeZones in database, how can I pass them dynamically?

I tried this in my code:

TimeZone timezone = null;
String timezone1 = null;
public SchedulerBean(String timezone2) 
{
     this.timezone1 = timezone2;
  //constructor
}

@Scheduled(cron="0 0 8 * * ?", zone =timezone.getTimeZone(timezone1) ) //Error at this line
public void sendQuestionNotif() 
{
  //......code
}

Here is the error I am getting,

*Type mismatch: cannot convert from TimeZone to String*

Please help me. Because I want to trigger cron based on timezones. TIA.

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Jul 27, 2015

Annotation parameters cannot be set dynamically. You can do it programmatically, like this

class Scheduler implements Runnable {
    public Scheduler(TaskScheduler scheduler, String timezone, String cron) {
        scheduler.schedule(this, new CronTrigger(cron, TimeZone.getTimeZone(timezone)));
    }

    @Override
    public void run() {
        //
    }
}