参考了https://www.itdaan.com/blog/2017/06/26/e6d6016d13d9bdfce53546516bc498b8.html
使用的spring boot版本是1.5.10
完整的pom文件如下:
4.0.0
org.example
quartz_test
1.0-SNAPSHOT
8
8
4.3.9.RELEASE
org.springframework.boot
spring-boot-starter-parent
1.5.10.RELEASE
junit
junit
4.11
test
org.springframework
spring-test
test
org.springframework
spring-context
${springframework.version}
org.springframework
spring-context-support
${springframework.version}
org.springframework
spring-tx
${springframework.version}
org.springframework.boot
spring-boot-starter-web
org.quartz-scheduler
quartz
2.3.0
com.novemberain
quartz-mongodb
2.1.0
org.springframework.boot
spring-boot-starter-data-mongodb
org.springframework.boot
spring-boot-maven-plugin
每个依赖都比较好理解,或许有用不到的依赖,暂时没有一一排查.
quartz.properties文件如下:
org.quartz.scheduler.instanceName=funScheduler
org.quartz.jobStore.class=com.novemberain.quartz.mongodb.MongoDBJobStore
org.quartz.jobStore.mongoUri=mongodb://localhost:27017
org.quartz.jobStore.dbName=somefun
org.quartz.jobStore.collectionPrefix=quartz
org.quartz.threadPool.threadCount=1
其中比较重要的就是threadCount属性,如果定时任务多于线程数,会导致misfire问题,在https://www.jianshu.com/p/acc777433963这篇文章中有讲.
代码部分,quartz使用的关键组件包括scheduler, job, trigger.
scheduler由SchedulerFactoryBean产生,代码如下
@Configuration
public class QuartzConfiguration {
/**
* Here we integrate quartz with Spring and let Spring manage initializing
* quartz as a spring bean.
*
// * @return an instance of {@link SchedulerFactoryBean} which will be managed
* by spring.
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
scheduler.setApplicationContextSchedulerContextKey("applicationContext");
scheduler.setConfigLocation(new FileSystemResource("config/quartz.properties"));
scheduler.setWaitForJobsToCompleteOnShutdown(true);
scheduler.setAutoStartup(true);
scheduler.setStartupDelay(30);
return scheduler;
}
}
其中quartz.properties文件放在和jar包同级目录的config文件夹下(项目中也是如此);如果只是放在resources下, 可以用new ClassPathResource("quartz.properties")
,根据情况来.
接下来是job,简单的一个打印:
public class BroadcastScheduleJobCore implements Job{
@Override
public void execute(JobExecutionContext context) {
try {
Object id = context.getMergedJobDataMap().get("id");
System.out.println(id + "-start");
Thread.sleep(10*1000);
System.out.println(id + "-end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
从context中获取id参数,打印出来;参数添加在下面创建任务的代码中.
创建任务并开始调度的关键代码如下:
public static void createScheduleJob(Scheduler scheduler, String jobId) {
try {
//构建job信息
JobDetail jobDetail = JobBuilder.newJob(BroadcastScheduleJobCore.class).withIdentity(getJobKey(jobId)).build();
jobDetail.getJobDataMap().put("id", jobId);
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 31 * * * ? *")
.withMisfireHandlingInstructionFireAndProceed();
//按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId)).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
scheduler.start();
} catch (Exception e) {
e.printStackTrace();
}
}
把三个东西串起来的loader代码如下:
@Component
public class BroadcastLoader {
private final Scheduler scheduler;
@Autowired
public BroadcastLoader(Scheduler scheduler) {
this.scheduler = scheduler;
init();
}
private void init() {
String[] jobIds = new String[]{"id1", "id2"};
for (String jobId:jobIds) {
BroadcastScheduleUtil.createScheduleJob(scheduler, jobId);
}
}
}
到此直接启动Application类就可以从日志中看到任务执行,当然和你的cron设置有关.