javaquartz-scheduler

How to pass instance variables into Quartz job?


I wonder how to pass an instance variable externally in Quartz?

Below is pseudo code I would like to write. How can I pass externalInstance into this Job?

public class SimpleJob implements Job {
        @Override
        public void execute(JobExecutionContext context)
                throws JobExecutionException {

            float avg = externalInstance.calculateAvg();
        }
}

Solution

  • you can put your instance in the schedulerContext.When you are going to schedule the job ,just before that you can do below:

    getScheduler().getContext().put("externalInstance", externalInstance);
    

    Your job class would be like below:

    public class SimpleJob implements Job {
        @Override
        public void execute(JobExecutionContext context)
                throws JobExecutionException {
            SchedulerContext schedulerContext = null;
            try {
                schedulerContext = context.getScheduler().getContext();
            } catch (SchedulerException e1) {
                e1.printStackTrace();
            }
            ExternalInstance externalInstance =
                (ExternalInstance) schedulerContext.get("externalInstance");
    
            float avg = externalInstance.calculateAvg();
        }
    }
    

    If you are using Spring ,you can actually using spring's support to inject the whole applicationContext like answered in the Link