Spring @Scheduled annotation

17,232

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() {
        //
    }
}
Share:
17,232
Chandz
Author by

Chandz

JAVA and J2EE IT Fresher.

Updated on June 04, 2022

Comments

  • Chandz
    Chandz almost 2 years

    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.