Dynamically scheduling jobs: using cron trigger in groovy

北慕城南 提交于 2019-12-22 01:36:57

问题


I am still playing around with quartz scheduler.I created the below job using grails create-job ,what i am trying to do here is simple, that is create a trigger and try to run the execute method.once this basic code runs i want to create multiple triggers each with different cron schedule value, inside a for loop(multiple triggers with different execution time) and run the execute method and do sched.scheduleJob(triggerName) over list of these triggers

import org.quartz.*
import org.quartz.Trigger
import static org.quartz.JobBuilder.*;
import static org.quartz.CronScheduleBuilder.*;
import static org.quartz.TriggerBuilder.*;
public class TrialJob 
{
    public static void main(String[] args)
    {
       JobDetail job = JobBuilder.newJob(TestJob.class).withIdentity("dummyJobName1","group11").build();

       CronTrigger trigger = newTrigger().withIdentity("trigger","group1").withSchedule(cronSchedule("0 55 15 * * ?")).build();

       Scheduler scheduler = new StdSchedulerFactory().getScheduler();

       scheduler.scheduleJob(job,trigger);

       scheduler.start();

       //while(true){};
    }    

    public static class TestJob implements Job 
    { 
       public void execute(JobExecutionContext context) throws JobExecutionException 
       {
           println "inside execute "
       }        
    }
}

回答1:


First of all the code provided doesn't compile. There's an attempt of assigning instance of class org.quartz.impl.StdSchedulerFactory to a variable declared as org.quartz.Scheduler.

Secondly the program runs well and the job is scheduled but the it exists before any output is caught. To prove it run below example with uncommented //while(true){}; line. The example is taken from here.

@Grab(group='org.quartz-scheduler', module='quartz', version='2.2.1') 

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class CronTriggerExample {
    public static void main( String[] args ) throws Exception {
        JobDetail job = JobBuilder.newJob(HelloJob.class)
        .withIdentity("dummyJobName1", "group11").build();

        Trigger trigger = TriggerBuilder
        .newTrigger()
        .withIdentity("dummyTriggerName1", "group11")
        .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
        .build();


        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger); 

        //while(true){};
    }
}

public class HelloJob implements Job {
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("Hello Quartz!");    
    }
}

Hope that helped you.



来源:https://stackoverflow.com/questions/27870823/dynamically-scheduling-jobs-using-cron-trigger-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!