原创

Quartz给任务方法传递参数

温馨提示:
本文最后更新于 2023年02月15日,已超过 514 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

1.需求场景

   在我们使用Quartz作为作业调度框架时,部分场景下需要给具体任务类传递参数,比如id,姓名等。

2. 解决方案

      2.1 声明作业的时候携带参数

               

         Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(task.getJobClass()).newInstance()
                    .getClass());
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(task.getJobName(), task.getJobGroup())// 任务名称和组构成任务key
                    .build();
            //携带参数
            jobDetail.getJobDataMap().put("id","123456");
            jobDetail.getJobDataMap().put("name","www.365codemall.com");

         在任务方法中获取参数

@DisallowConcurrentExecution //作业不并发
@Component
public class HelloWorldJob1 extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String id = jobExecutionContext.getJobDetail().getJobDataMap().getString("id");
        String name = jobExecutionContext.getJobDetail().getJobDataMap().getString("name");
        System.out.println(id);
        System.out.println(name);
    }
}<br/>

 

2.2  声明作业的时候携带参数

    // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getJobName(), task.getJobGroup())// 触发器key
                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())).startNow().build();
            //策略中携带参数
            trigger.getJobDataMap().put("id","789");
            trigger.getJobDataMap().put("name","www.365codemall.com");

       在任务方法中获取参数

@DisallowConcurrentExecution //作业不并发
@Component
public class HelloWorldJob1 extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String id = jobExecutionContext.getTrigger().getJobDataMap().getString("id");
        String name = jobExecutionContext.getTrigger().getJobDataMap().getString("name");
        System.out.println(id);
        System.out.println(name);
    }
}

2.3  使用MergedJobDataMap

通过JobDetail 或者 Trigger 携带的参数,也可以通过 MergedJobDataMap获取

@DisallowConcurrentExecution //作业不并发
@Component
public class HelloWorldJob1 extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String id = jobExecutionContext.getMergedJobDataMap().getString("id");
        String name = jobExecutionContext.getMergedJobDataMap().getString("name");
        System.out.println(id);
        System.out.println(name);
    }
}

如果JobDetail 和 Trigger 携带了相同key值得参数,MergedJobDataMap会优先获取Trigger携带的参数

       

正文到此结束
本文目录