Debojit
Debojit

Reputation: 628

Altering Quartz Job Schedule


I'm looking into scheduling my application with Quartz, but in all cases, the job trigger seems to be a one-time activity, and changes to the trigger need the application to be re-deployed to take effect.
Is there any way I can have the job trigger check for changes to the job schedule without having to redeploy the code?
Thanks,

Upvotes: 2

Views: 3452

Answers (1)

Jeff
Jeff

Reputation: 396

  1. Trap some user-driven event, like updating a text value, for example a cron-string to schedule a job
  2. Locate and unschedule/delete the old job and trigger.
  3. Schedule the job again, using the new trigger.

    public static <T> T scheduleCronJob(Class<T> clazz, String cronString, String uid){
        try{            
            if(cronString == null){
                throw new CronStringConfigurationException();
            }
    
            String jobGroupName = "cronJobsGroup";
            String jobName = "cronJob" + uid;
            String triggerGroupName = "cronTriggers";
            String triggerName = "triggerFor" + uid;
    
            JobDetail jobDetail = new JobDetail(jobName, jobGroupName, clazz);
    
            CronTrigger trigger = new CronTrigger(
                    triggerName, triggerGroupName, 
                    jobName, jobGroupName, 
                    cronString);
    
            JobDataMap jobDataMap = new JobDataMap();
            jobDetail.setJobDataMap(jobDataMap);
    
            getScheduler().scheduleJob(jobDetail, trigger);
        } catch(Exception e){
        // print error message, throw stack trace
        }
        return null;
    }
    
    public static void reloadCronJob(Class clazz, String cronString, String uid) throws SystemException, ParseException, SchedulerException, 
        CronStringConfigurationException, PortalException{
        // locate the job 
        String jobGroupName = "cronJobs";
        String jobName = "jobFor" + uid;
    
        if(cronString == null){
            throw new CronStringConfigurationException();
        }
    
        JobDetail jobDetail = null;
        Class<?> jobClass = null;
    
        // remove the old job/trigger if it exists
        try{
            jobDetail = scheduler.getJobDetail(jobName, jobGroupName);
            if(jobDetail != null){
                jobClass = jobDetail.getJobClass();
            }
            scheduler.deleteJob(jobName, jobGroupName);
        } catch(Exception e){
            e.printStackTrace();
        }
    
        if(jobClass == null){
            jobClass = clazz;
        }
    
        // create a new trigger
        scheduleCronJob(jobClass, expandoColumnName, uid);
    
        System.out.println("(re)scheduled job " + jobName + " using new cron string " + cronString);
    }
    

Upvotes: 1

Related Questions