1、maven引入quartz包
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
2、创建定时任务工厂类
@Component
public class JobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
final Object jobInstance = super.createJobInstance(bundle);
beanFactory.autowireBean(jobInstance);
return jobInstance;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.beanFactory = applicationContext.getAutowireCapableBeanFactory();
}
}
3、创建定时任务抽象类
public abstract class AbstractTask implements Job {
private Logger logger = LoggerFactory.getLogger(AbstractTask.class);
protected abstract void executeInternal(JobExecutionContext context) throws Exception;
private String key;
private Long dataBaseId;
@Override
public void execute(JobExecutionContext context) {
try {
executeInternal(context);
} catch (Exception e) {
logger.error(e.getMessage(), e);
logger.error("job execute failed!");
}
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Long getDataBaseId() {
return dataBaseId;
}
public void setDataBaseId(Long dataBaseId) {
this.dataBaseId = dataBaseId;
}
}