How to pass instance variables into Quartz job?

后端 未结 6 1678
遇见更好的自我
遇见更好的自我 2021-01-31 16:55

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?



        
6条回答
  •  情书的邮戳
    2021-01-31 17:42

    Quartz has a simple way to grep params from JobDataMap using setters

    I am using Quartz 2.3 and I simply used setter to fetch passed instance objects

    For example I created this class

    public class Data implements Serializable {
        @JsonProperty("text")
        private String text;
    
        @JsonCreator
        public Data(@JsonProperty("b") String text) {this.text = text;}
    
        public String getText() {return text;}
    }
    

    Then I created an instance of this class and put it inside the JobDataMap

    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("data", new Data(1, "One!"));
    JobDetail job = newJob(HelloJob.class)
                    .withIdentity("myJob", "group")
                    .withDescription("bla bla bla")
                    .usingJobData(jobDataMap) // 

    And my job class looks like this

    public class HelloJob implements Job {
        Data data;
    
        public HelloJob() {}
    
        public void execute(JobExecutionContext context)
                throws JobExecutionException
        {
            String text = data.getText();
            System.out.println(text);
        }
    
        public void setData(Data data) {this.data = data;}
    }
    
    • Note: it is mandatory that the field and the setter matched the key

    This code will print One! when you schedule the job.

    That's it, clean and efficient

提交回复
热议问题