Quartz是开源组织OpenSymphony的一个作业调度框架,采用多线程架构,可伸缩性强,可集群扩展。Spring集成Quartz简单高效,只需实现Job接口,在方法execute()中添加业务逻辑

 

SpringBoot集成Quartz的方法详见上一篇博文,Spring集成Quartz实现定时任务和异步作业调度

 

Job.execute()方法中实现业务逻辑时,经常需要一些附加信息。Quartz提供了JobExecutionContext上下文通过JobDataMap传递数据。


代码文件

功能要点

设置数据

QuartzConfig.java

创建JobDetail或者Trigger时,调用usingJobData()设置数据

读取数据

QuartzJob.java

执行任务时,调用JobExecutionContext.getMergedJobDataMap()获取数据

 

代码

Github下载:https://github.com/rickding/HelloJava/tree/master/HelloQuartz

 

设置数据

JobDetail和Trigger都可以调用usingJobData()方法设置数据

@Configuration
@ConfigurationProperties("quartz")
public class QuartzConfig {
    @Bean
    public JobDetail quartzJob() {
        JobDataMap dataMap = new JobDataMap() {{
            put("job_str", "str_test");
        }};

        return JobBuilder.newJob(QuartzJob.class)
                .usingJobData(dataMap)
                .storeDurably()
                .build();
    }

    @Bean
    public Trigger quartzTrigger() {
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        JobDataMap dataMap = new JobDataMap() {{
            put("trigger_int", 333);
        }};

        return TriggerBuilder.newTrigger()
                .forJob(quartzJob())
                .withSchedule(scheduleBuilder)
                .usingJobData(dataMap)
                .build();
    }

}

 

读取数据

JobExecutionContext中读取信息,执行业务逻辑。

public class QuartzJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        // get data from context
        JobDataMap dataMap = context.getMergedJobDataMap();
        for (Map.Entry, Object> data : dataMap.entrySet()) {
            System.out.printf("%s = %s\n", data.getKey(), data.getValue());
        }

        // do work
    }
}

 

运行输出

trigger_int = 333
job_str = str_test