Friday, 25 March 2016

How to run multiple jobs in Quartz ?



In Quartz scheduler framework, each job will be attached to an unique trigger and run it by scheduler.

1. Create 3 Quartz’s jobs

public class Job1 implements Job { 
   @Override
   public void execute(JobExecutionContext context) throws JobExecutionException {
      System.out.println("Job 1 is runing");
   }
}

public class Job2 implements Job {
   @Override
   public void execute(JobExecutionContext context) throws JobExecutionException {
      System.out.println("Job 2 is runing");
   }
}

public class Job3 implements Job {
   @Override
   public void execute(JobExecutionContext context) throws JobExecutionException {
      System.out.println("Job 3 is runing");
   } 
}


2. Declare above 3 jobs, assign to 3 particular triggers and schedule it

JobKey jobKey1 = new JobKey("job1", "group1");
JobDetail job1 = JobBuilder.newJob(Job1.class).withIdentity(jobKey1).build();

JobKey jobKey2 = new JobKey("job2", "group1");
JobDetail job2 = JobBuilder.newJob(Job2.class).withIdentity(jobKey2).build();

JobKey jobKey3 = new JobKey("job3", "group1");
JobDetail job3 = JobBuilder.newJob(Job3.class).withIdentity(jobKey3).build();

Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("myTriggerName1", "group1")
    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build();
Trigger trigger2 = TriggerBuilder.newTrigger().withIdentity("myTriggerName2", "group1")
    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build();
Trigger trigger3 = TriggerBuilder.newTrigger().withIdentity("myTriggerName3", "group1")
    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build();

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

scheduler.start();
scheduler.scheduleJob(job1, trigger1);
scheduler.scheduleJob(job2, trigger2);
scheduler.scheduleJob(job3, trigger3);

No comments:

Post a Comment

Note: only a member of this blog may post a comment.