How to create a trigger object programmatically?

I am using Spring Quartz Scheduler, but I am not using an XML file. I want to programmatically create the whole configuration.

I wrote the following code.

package com.eaportal.service.impl; import java.text.ParseException; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.quartz.JobDetail; import org.springframework.scheduling.SchedulingException; import org.springframework.scheduling.quartz.CronTriggerBean; import org.springframework.scheduling.quartz.JobDetailBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import com.eaportal.service.intfc.AuctionWinnerService; public class NormalAuctionWinnerServiceImpl1 implements AuctionWinnerService { @SuppressWarnings("deprecation") public void declareWinner(int auctionId, Map<String, Object> parameterMap) { System.out.println("INSIDE DECLARE WINNER METHOD."); /** STEP 1 : INSTANTIATE TASK CLASS **/ NormalAuctionWinnerTask1 runMeTask = new NormalAuctionWinnerTask1(); System.out.println("FINISHED STEP 1"); /** STEP 2 : INSTANTIATE JOB DETAIL CLASS AND SET ITS PROPERTIES **/ Map<String,Object> jobDataAsMap = new HashMap<String,Object>(); jobDataAsMap.put("runMeTask",runMeTask); JobDetailBean jdb = new JobDetailBean(); jdb.setJobClass(NormalAuctionWinnerTask1.class); jdb.setJobDataAsMap(jobDataAsMap); System.out.println("FINISHED STEP 2"); /** STEP 3 : INSTANTIATE CRON TRIGGER AND SET ITS PROPERTIES **/ CronTriggerBean ctb = new CronTriggerBean(); Date d1 = new Date(); Date d2 = new Date(); d2.setMinutes(d1.getMinutes()+10); ctb.setStartTime(d1); ctb.setEndTime(d2); ctb.setJobDetail(jdb); try { ctb.setCronExpression("59 * * * * ? *"); } catch (ParseException e) { e.printStackTrace(); } /** STEP 4 : INSTANTIATE SCHEDULER FACTORY BEAN AND SET ITS PROPERTIES **/ SchedulerFactoryBean sfb = new SchedulerFactoryBean(); sfb.setJobDetails(new JobDetail[]{jdb}); try { sfb.start(); } catch (SchedulingException e) { e.printStackTrace(); } } } 

The code works, except that the trigger does not start coz. I did not ask him.

The problem here is the XML configuration, we have the schedulerFactoryBean triggers property, and we use the list to configure our triggers.

But I cannot set the same property programmatically. SchedulerFactoryBean has a setTriggers method that accepts a Trigger array but how to create this is a problem.

I have been on it for the last 4 hours until I acknowledge success.

Can anyone help me out here?

thanks

+4
source share
2 answers

I was able to do this using the Spring Scheduling Framework successfully.

I understand that this is a very old post, but since the content on this topic is rather scarce, it is better to post it here.

The main problem in the code for the first message is that afterPropertiesSet() not called for both the JobDetail object and the CronTrigger object. The afterProperties function does some processing of the entered values ​​before cron is ready to run.

In addition, I used MethodInvokingJobDetailFactoryBean instead of the regular JobDetail , since it gives more flexibility to the function that cron will call in this class.

Here is my code:

 package test.spring; import org.quartz.JobDetail; import org.quartz.Trigger; import org.springframework.context.support.GenericApplicationContext; import org.springframework.scheduling.SchedulingException; import org.springframework.scheduling.quartz.CronTriggerBean; import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import java.text.ParseException; public class ProgrammaticCron { public static void callWorkFlow() { System.out.println("Abhishek Jain"); } public static void main (String[] args) { try { GenericApplicationContext applicationContext = new GenericApplicationContext(); MethodInvokingJobDetailFactoryBean jdfb = new MethodInvokingJobDetailFactoryBean(); jdfb.setTargetClass(ProgrammaticCron.class); jdfb.setTargetMethod("callWorkFlow"); jdfb.setName("Trial program"); jdfb.afterPropertiesSet(); JobDetail jd = (JobDetail)jdfb.getObject(); CronTriggerBean ctb = new CronTriggerBean(); ctb.setJobDetail(jd); ctb.setName("Daily cron"); ctb.setJobName(jd.getName()); try { ctb.setCronExpression("59 * * * * ? *"); } catch (ParseException e) { e.printStackTrace(); } ctb.afterPropertiesSet(); SchedulerFactoryBean sfb = new SchedulerFactoryBean(); sfb.setJobDetails(new JobDetail[]{(JobDetail)jdfb.getObject()}); sfb.setTriggers(new Trigger[]{ctb}); sfb.afterPropertiesSet(); try { sfb.start(); } catch (SchedulingException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } } 

afterProperties() important, and from the afterProperties implementation of SchedulerFactoryBean you can understand that:

  //--------------------------------------------------------------------- // Implementation of InitializingBean interface //--------------------------------------------------------------------- public void afterPropertiesSet() throws Exception { if (this.dataSource == null && this.nonTransactionalDataSource != null) { this.dataSource = this.nonTransactionalDataSource; } if (this.applicationContext != null && this.resourceLoader == null) { this.resourceLoader = this.applicationContext; } // Create SchedulerFactory instance. SchedulerFactory schedulerFactory = (SchedulerFactory) BeanUtils.instantiateClass(this.schedulerFactoryClass); initSchedulerFactory(schedulerFactory); if (this.resourceLoader != null) { // Make given ResourceLoader available for SchedulerFactory configuration. configTimeResourceLoaderHolder.set(this.resourceLoader); } if (this.taskExecutor != null) { // Make given TaskExecutor available for SchedulerFactory configuration. configTimeTaskExecutorHolder.set(this.taskExecutor); } if (this.dataSource != null) { // Make given DataSource available for SchedulerFactory configuration. configTimeDataSourceHolder.set(this.dataSource); } if (this.nonTransactionalDataSource != null) { // Make given non-transactional DataSource available for SchedulerFactory configuration. configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource); } // Get Scheduler instance from SchedulerFactory. try { this.scheduler = createScheduler(schedulerFactory, this.schedulerName); populateSchedulerContext(); if (!this.jobFactorySet && !(this.scheduler instanceof RemoteScheduler)) { // Use AdaptableJobFactory as default for a local Scheduler, unless when // explicitly given a null value through the "jobFactory" bean property. this.jobFactory = new AdaptableJobFactory(); } if (this.jobFactory != null) { if (this.jobFactory instanceof SchedulerContextAware) { ((SchedulerContextAware) this.jobFactory).setSchedulerContext(this.scheduler.getContext()); } this.scheduler.setJobFactory(this.jobFactory); } } finally { if (this.resourceLoader != null) { configTimeResourceLoaderHolder.remove(); } if (this.taskExecutor != null) { configTimeTaskExecutorHolder.remove(); } if (this.dataSource != null) { configTimeDataSourceHolder.remove(); } if (this.nonTransactionalDataSource != null) { configTimeNonTransactionalDataSourceHolder.remove(); } } registerListeners(); registerJobsAndTriggers(); } 

As you can see, all tasks such as getting a scheduler and registering a task using triggers are performed as part of this function.

+8
source

The main problem should be that you need to schedule a task:

 scheduler.scheduleJob(jobDetail, trigger); 

And I don't know how this is done for Spring Quarz Beans, but the usual Quarz jobs and trigger must have a name and a group! And you may need to run the scheduler: scheduler.start();

I changed your code a bit, that it works without spring, and they all ignore the material to demonstrate how it works:

batch test;

 import java.text.ParseException; import java.util.Date; import org.quartz.CronTrigger; import org.quartz.Job; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.StdSchedulerFactory; public class Demo { public static class TestJob implements Job{ @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { System.out.println("execute"); } } public static void declareWinner() throws SchedulerException, ParseException { JobDetail jobDetail = new JobDetail("job","group",Demo.TestJob.class); CronTrigger trigger = new CronTrigger("trigger","group"); trigger.setStartTime(new Date()); trigger.setEndTime(new Date(new Date().getTime() + 10 * 60 * 1000)); trigger.setCronExpression("* * * * * ? *"); /** STEP 4 : INSTANTIATE SCHEDULER FACTORY BEAN AND SET ITS PROPERTIES **/ SchedulerFactory sfb = new StdSchedulerFactory(); Scheduler scheduler = sfb.getScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } public static void main (String[] args) throws SchedulerException, Exception { declareWinner(); Thread.sleep(10000); } } 
-1
source

Source: https://habr.com/ru/post/1337317/


All Articles