写在前面
最近要做一个动态的定时任务需求(多个定时任务),百度找了好多资料还是没有头绪,最后看到了这个
https://blog.csdn.net/lyg_come_on/article/details/78223344#commentBox
资料解决我的问题,感谢作者!
准备
maven
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.3.0</version>
</dependency>
启动类加上
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
public class xxxxApplication{
public static void main(String[] args) {
SpringApplication.run(xxxxApplication.class, args);
}
}
代码
1、创建一个SchedulerListener类,并实现ApplicationListener,并编写自己的schedulerFactoryBean
@Configuration
public class MySchedulerListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
MyScheduler myScheduler;
@Autowired
MyJobFactory myJobFactory;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
try {
myScheduler.schedulerJob();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Bean(name = "mySchedulerFactoryBean")
public SchedulerFactoryBean mySchedulerFactory() {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
bean.setOverwriteExistingJobs(true);
bean.setStartupDelay(1);
bean.setJobFactory(myJobFactory);
return bean;
}
}
2、重新AdaptableJobFactory工厂,从spring获得bean(这个是很重要的)
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
* 重新AdaptableJobFactory工厂,从spring获得bean(这个是很重要的)
*/
@Component
public class MyJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
//注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
3、编写job
job1
public class MySchedulerJob implements Job {
private SimpleDateFormat dateFormat() {
return new SimpleDateFormat("HH:mm:ss");
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("AAAA: The time is now " + dateFormat().format(new Date()));
}
}
job2
public class MySchedulerJob2 implements Job {
private SimpleDateFormat dateFormat() {
return new SimpleDateFormat("HH:mm:ss");
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("AAAA: The time is now " + dateFormat().format(new Date()));
}
}
4、编写Scheduler,并添加job
@Component
public class MyScheduler {
public void schedulerJob() throws SchedulerException {
ApplicationContext annotationContext = SpringUtil.getApplicationContext();
StdScheduler stdScheduler = (StdScheduler) annotationContext.getBean("mySchedulerFactoryBean");//获得上面创建的bean
Scheduler myScheduler =stdScheduler;
startScheduler1(myScheduler);
startScheduler2(myScheduler);
myScheduler.start();
}
public void startScheduler1(Scheduler scheduler) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(MySchedulerJob.class).withIdentity("job1", "jobGroup1").build();
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
.withSchedule(cronScheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
}
public void startScheduler2(Scheduler scheduler) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(MySchedulerJob2.class).withIdentity("job2", "jobGroup2").build();
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "triggerGroup2")
.withSchedule(cronScheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
}
}
5、SpringUtil获得application
@Component
public class SpringUtil implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(SpringUtil.class);
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
logger.info("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getApplicationContext()获取applicationContext对象,applicationContext="
+ SpringUtil.applicationContext + "========");
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 通过name获取 Bean.
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) getApplicationContext().getBean(name);
}
// 通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
// 通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
写在最后
1、如果ApplicationContext为null的话请检查注解
2、运行成功(我在本机测试)。
3、本篇只是代码的搬运工,在copy的运行成功要自己理解一下,才能成为自己的东西
4、再次感谢作者
作者:安静的写个代码
来源:CSDN
原文:https://blog.csdn.net/lyg_come_on/article/details/78223344