How to add multiple triggers for a job in Quartz
In this example we will see how we can add multiple trigger for a single job in Quartz scheduler.
We will follow the following steps :
1.At first lets create a job class.
2.Now lets create a class that will schedule the TestJob with two trigger
After running the program, you will see that the job is executed in different intervals by the above two trigger.
We will follow the following steps :
1.At first lets create a job class.
package com.techniqpatch.quartz import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class TestJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Job is runing"); } }
package com.techniqpatch.quartz;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzTest {
Scheduler scheduler;
public void schedule(String[] args) throws ParseException,
SchedulerException {
SchedulerFactory factory = new StdSchedulerFactory();
scheduler = factory.getScheduler();
Map<JobDetail, List<Trigger>> triggersAndJobs = new HashMap<JobDetail, List<Trigger>>();
List triggerList = new ArrayList();
String groupName = "GroupName";
String jobName = "JobName";
JobKey jobKey = new JobKey(jobName, groupName);
String triggerName = jobName;
List createdTrigger = new ArrayList();
createdTrigger.add("02 01 02 1 * * ?");
createdTrigger.add("02 01 03 5 * * ?");
JobDetail job = JobBuilder.newJob(TestJob.class)
.withIdentity(jobKey).usingJobData("groupName", groupName)
.usingJobData("jobName", jobName).build();
CronTrigger trigger;
CronTrigger trigger1;
trigger = (CronTrigger) TriggerBuilder
.newTrigger()
.withIdentity(triggerName + "0", groupName)
.withSchedule(
CronScheduleBuilder.cronSchedule(createdTrigger.get(0)))
.build();
trigger1 = (CronTrigger) TriggerBuilder
.newTrigger()
.withIdentity(triggerName + "1", groupName)
.withSchedule(
CronScheduleBuilder.cronSchedule(createdTrigger.get(1)))
.build();
triggerList.add(trigger);
triggerList.add(trigger1);
triggersAndJobs.put(job, triggerList);
if (!scheduler.isStarted()) {
scheduler.start();
}
scheduler.scheduleJobs(triggersAndJobs, true);
}
}
Thanks man. It really helped.
ReplyDeleteThanks
ReplyDelete