Spring @Scheduled annotation
Asked Answered
W

1

4

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.

Withrow answered 27/7, 2015 at 10:52 Comment(0)
A
5

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() {
        //
    }
}
Araminta answered 27/7, 2015 at 11:36 Comment(3)
Thank you so much. If I use ur answer, then do I need to still use @Scheduled(cron="cronExpression", Timezone timezone) on the method which does work for me based on cron expression?Withrow
No, you dont. But you can create Scheduler as a bean from contextAraminta
Can you provide the solution you got ? it would be very helpful for me and for other usersCrinite

© 2022 - 2024 — McMap. All rights reserved.