How to set date and time in Quartz Schedular from database

174 views Asked by At

I am trying to set date and time from database in Quartz Schedular but is unable to do so. Please help me out.

Here is my code:

public class CroneScheduler {

    public CroneScheduler() throws Exception {

        SchedulerFactory sf = new StdSchedulerFactory();

        Scheduler sche = sf.getScheduler();

        sche.start();

        JobDetail jDetail;
        jDetail = new JobDetail("Newsletter", "NJob", MyJob.class);

        //"0 0 12 * * ?" Fire at 12pm (noon) every day
        //"0/2 * * * * ?" Fire at every 2 seconds every day
        CronTrigger crTrigger = new CronTrigger("cronTrigger", "NJob", "0/2 * * * * ?");

        sche.scheduleJob(jDetail, crTrigger);
    }
}
1

There are 1 answers

0
flyingfox On

If the version of quartz is 1.7.2,then you can use below code:

public void resetJob(String expression){
    ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    Scheduler scheduler = (Scheduler) applicationContext.getBean("testScheduler");
    try {
        CronTriggerBean trigger = new CronTriggerBean();
        trigger.setCronExpression(expression);
        trigger.setName("testJobTrigger");
        trigger.setGroup(Scheduler.DEFAULT_GROUP);
        trigger.setJobName("testJobDetail");
        scheduler.rescheduleJob("testJobTrigger", Scheduler.DEFAULT_GROUP, trigger);
    } catch (SchedulerException | ParseException e) {
        e.printStackTrace();
    }
}

If the version of quartz is newer than 1.7.2,you can use below code:

public void resetJob(String expression){
        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        Scheduler scheduler = (Scheduler) applicationContext.getBean("testScheduler");
        CronTriggerImpl trigger = null;
        try {
            TriggerKey triggerKeys = TriggerKey.triggerKey("testJobTrigger",Scheduler.DEFAULT_GROUP);
            trigger = new CronTriggerImpl();
            trigger.setCronExpression(expression);
            trigger.setKey(triggerKeys);//keep key the same
            scheduler.rescheduleJob(triggerKeys,trigger);
        } catch (ParseException | SchedulerException e) {
            e.printStackTrace();
        }
}