How to pass instance variables into Quartz job?

不想你离开。 提交于 2019-12-02 18:05:39
Rips

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

While scheduling the job using a trigger, you would have defined JobDataMap that is added to the JobDetail. That JobDetail object will be present in the JobExecutionContext passed to the execute() method in your Job. So, you should figure out a way to pass your externalInstance through the JobDataMap. HTH.

Harsh Maheswari

Solve this problem by creating one interface with one HashMap putting required information there.

Implement this interface in your Quartz Job class this information will be accessible.

In IFace

Map<JobKey,Object> map = new HashMap<>();

In Job

map.get(context.getJobDetail().getKey()) =>  will give you Object

This is the responsibility of the JobFactory. The default PropertySettingJobFactory implementation will invoke any bean-setter methods, based on properties found in the schdeuler context, the trigger, and the job detail. So as long as you have implemnted an appropriate setContext() setter method you should be able to do any of the following:

scheduler.getContext().put("context", context);

Or

Trigger trigger = TriggerBuilder.newTrigger()
  ...
  .usingJobData("context", context)
  .build()

Or

JobDetail job = JobBuilder.newJob(SimpleJob.class)
  ...
  .usingJobData("context", context)
  .build()

Or if that isn't enough you can provide your own JobFactory class which instantiates the Job objects however you please.

Add the object to the JobDataMap:

JobDetail job = JobBuilder.newJob(MyJobClass.class)
                          .withIdentity("MyIdentity",
                                        "MyGroup")
                          .build();
job.getJobDataMap()
   .put("MyObject",
        myObject);

Access the data from the JobDataMap:

var myObject = (MyObjectClass) context.getJobDetail()
                                      .getJobDataMap()
                                      .get("carrier");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!