Quartz是開源組織OpenSymphony的一個做業調度框架,採用多線程架構,可伸縮性強,可集羣擴展。Spring集成Quartz簡單高效,只需實現Job接口,在方法execute()中添加業務邏輯。
java
SpringBoot集成Quartz的方法詳見上一篇博文,Spring集成Quartz實現定時任務和異步做業調度git
在Job.execute()方法中實現業務邏輯時,常常須要一些附加信息。Quartz提供了JobExecutionContext上下文經過JobDataMap傳遞數據。github
代碼文件多線程 |
功能要點架構 |
|
設置數據框架 |
QuartzConfig.java異步 |
建立JobDetail或者Trigger時,調用usingJobData()設置數據ide |
讀取數據ui |
QuartzJob.javaspa |
執行任務時,調用JobExecutionContext.getMergedJobDataMap()獲取數據 |
l 代碼
Github下載:https://github.com/rickding/HelloJava/tree/master/HelloQuartz
l 設置數據
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();
}
}
l 讀取數據
從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<String, Object> data : dataMap.entrySet()) {
System.out.printf("%s = %s\n", data.getKey(), data.getValue());
}
// do work
}
}
l 運行輸出
trigger_int = 333
job_str = str_test