JobDataMap传递参数_02

JobDataMap属于JobDetail的一部分
可以在构建JobDataMap时传递参数

取出参数2种形式:
第1种:可以从execute方法的上下文中取出参数
第2种:在Job类中,定义参数名称,完成getset方法

推荐使用第2种+lombok

添加参数

        //创建JobDetail
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                //唯一标识
                .withIdentity("jobDetail1", "group1")
                //添加参数通过usingJobData方法,传递给job
                .usingJobData("name","yx")
                .build();

第1种:可以从execute方法的上下文中取出参数

package com.gblfy.job;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.time.LocalTime;

public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        LocalTime localTime = LocalTime.now();
        /*
          1.从上下文中先获取getJobDetail
          2.再从getJobDetail中获取JobDataMap
          3.最后,从JobDataMap中,根据key获取对应属性的值
         */
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String name = jobDataMap.getString("name");

        System.out.println("hello " + name + "我正在执行" + localTime);
    }
}

JobDataMap传递参数_02_第1张图片
第2种:在Job类中,定义参数名称,完成getset方法

package com.gblfy.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.time.LocalTime;

public class MyJob implements Job {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        LocalTime localTime = LocalTime.now();
        System.out.println("hello " + name + "我正在执行" + localTime);
    }
}

JobDataMap传递参数_02_第2张图片
为了减少代码,建议引入lombok

 </dependency>
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.12</version>
      </dependency>

刚才的代码,简化为

package com.gblfy.job;

import lombok.Getter;
import lombok.Setter;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.time.LocalTime;

public class MyJob implements Job {

    @Getter@Setter
    private String name;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        LocalTime localTime = LocalTime.now();
        System.out.println("hello " + name + "我正在执行" + localTime);
    }
}

JobDataMap传递参数_02_第3张图片
效果是一样的

你可能感兴趣的:(Quartz,传递参数)