1. 程式人生 > >quartz定時器 Job的execute使用動態引數

quartz定時器 Job的execute使用動態引數

@GetMapping({"/addSearchIndexBySite"})
    public JsonResult addSearchIndexBySite(@RequestParam(required = false) String site) throws SchedulerException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        JobDTO dto = new JobDTO();
        dto.setBeanName("tech.liveeasy.platform.kapok.elt.scheduler.UpdateSearchIndexJob"
); dto.setJobName("updateSearchIndexJob" + site); dto.setTriggerName("updateSearchIndexTrigger" + site); dto.setCronExpression("0 0 0 * * ? ");//每天0點 JobDetail jobDetail = JobBuilder.newJob(UpdateSearchIndexJob.class) .withIdentity(dto.getJobName()) .usingJobData
("site", site)//在此處新增需要用的引數即可 .build(); CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(dto.getCronExpression()); Trigger cronTrigger = newTrigger() .withIdentity(dto.getTriggerName()) .startNow() .withSchedule
(scheduleBuilder) .build(); try { scheduler.scheduleJob(jobDetail, cronTrigger); } catch (ObjectAlreadyExistsException e) { String result = "Unable to store Job, because one already exists with this identification."; return new JsonResult(ResultCode.SYS_ERROR, "異常", result); } return new JsonResult(ResultCode.SUCCESS, "成功", dto); }
@Component
public class UpdateSearchIndexJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        String site = null;
        try {//獲取引數使用
            context.getMergedJobDataMap().getString("site");
        } catch (Exception e){
            site = null;
        }
 }
也可以這麼用

trigger = trigger.getTriggerBuilder()
                .withIdentity(triggerKey)
                .usingJobData("site", jobDTO.getSite())
                .withSchedule(scheduleBuilder)
                .build();



site = context.getTrigger().getJobDataMap().getString("site");