Thursday, March 19, 2015

How to pass parameters to a Quartz job

In your Job class(implementation of org.quartz.Job interface) you don't have a way to set external parameters. What you can do is putting parameters in to the SchedulerContext when scheduling the job and get them back in the execute() method of the job.
See below example.

This is your main class where you set the scheduler.
import java.util.Date;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class TestQuartz {

  public static void main(String[] args) throws Exception {
    JobBuilder jobBuilder = JobBuilder.newJob(MyJob.class);
    JobDetail job = jobBuilder.withIdentity("myJob", "group1").build();
    Date sheduleTime = new Date(new Date().getTime() + 5000);
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startAt(sheduleTime).build();
    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    //Below line sets a variable named myContextVar in SchedulerContext.
    //Not only strings, you can set any type of object here.
    scheduler.getContext().put("myContextVar", "Hello, this text is from context.");
    scheduler.start();
    scheduler.scheduleJob(job, trigger);
  }
}

Now in your Job class you can get that variable from the SchedulerContext as below.
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;

public class MyJob implements Job {

  @Override
  public void execute(JobExecutionContext arg0) throws JobExecutionException {
    try {
      SchedulerContext schedulerContext = arg0.getScheduler().getContext();
      //Below line gets the value from context.
      //Just get it and cast it in to correct type
      String objectFromContext = (String) schedulerContext.get("myContextVar");
      System.out.println(objectFromContext);
    } catch (SchedulerException e1) {
      e1.printStackTrace();
    }
  }
}

1 comment:

  1. In my case, when the job runs, the SchedulerContext comes as org.quartz.SchedulerContext@0 and any variable set inside it comes as null.

    ReplyDelete