文章目录
- 一、使用示例
- 二、运行原理
一、使用示例
自定义 job:
@Slf4j
public class MyJob extends QuartzJobBean {@Overrideprotected void executeInternal(JobExecutionContext context) throws JobExecutionException {log.info("MyJob start...");long start = System.currentTimeMillis();MyService myService = (MyService) context.getMergedJobDataMap().get("myService");try {myService.func();} catch (Exception e) {log.error("MyJob error: ", e);}long end = System.currentTimeMillis();log.info("MyJob end in {} ms", end - start);}
}
配置 detail、trigger 和 schedule:
@Configuration
public class QuartzConfig {@Setter(onMethod_ = {@Autowired})private MyService myService;@Beanpublic JobDetailFactoryBean myJobDetail() {JobDetailFactoryBean detail = new JobDetailFactoryBean();detail.setJobClass(MyJob.class);detail.setDurability(true);Map<String, Object> jobData = new HashMap<>();jobData.put("myService", myService);detail.setJobDataAsMap(jobData);return detail;}@Beanpublic CronTriggerFactoryBean myJobTriggerBean() {CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();trigger.setJobDetail(Objects.requireNonNull(myJobDetail().getObject()));trigger.setCronExpression("*/5 * * * * ?"); // 每 5 秒钟执行一次return trigger;}@Beanpublic SchedulerFactoryBean schedulerFactoryBean() {SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();schedulerFactoryBean.setTriggers(myJobTriggerBean().getObject());return schedulerFactoryBean;}
}
二、运行原理
SchedulerFactoryBean
重写了 Lifecycle
的 start()
方法,该方法会在 Spring 容器启动时自动执行,从而启动定时任务。
此外,JobDetailFactoryBean
和 CronTriggerFactoryBean
均实现了 FactoryBean 和 InitializingBean
,它们会在执行 afterPropertiesSet()
时初始化并 set 对应的 JobDetail
和 CronTrigger
,并在调用 getObject()
时返回。
参考:
https://juejin.cn/post/6844903954615107597
https://juejin.cn/post/7086353052222881829