我访问了很多博客发现他们使用Quratz都采用了数据库,让我误以为必须采用数据库,然后当我提出要创建表这个可笑的要求时,他们和我说
不用数据库啊,我们只是简单的借用一下定时,不需要数据库的。
啊这,我有一点尴尬,找个理由说我看博客上都用了数据库,然后我没建表好像又报错所以才以为要表。
下面我将贴出不用数据库来运行Quratz定时器。
由于pom采用SpringBoot内置的就好,所以就不贴pom了,在创建SpringBoot项目时记得选取。
配置文件application.properties
org.quartz.scheduler.instanceName = quartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
# 实例化ThreadPool时,使用的线程类为SimpleThreadPool
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
# threadCount和threadPriority将以setter的形式注入ThreadPool实例
# 并发个数
org.quartz.threadPool.threadCount = 5
# 优先级
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
org.quartz.jobStore.misfireThreshold=50000
# 默认存储在内存中
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.is-clustered=true
#配置定时
job1 = job1
group1 = group1
cron = 0/20 * * * * ?
启动类 Application.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import com.pwc.demo.factory.MyJobFactory;
@SpringBootApplication
@Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
private MyJobFactory myJobFactory;
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(myJobFactory);
System.out.println("myJobFactory:"+myJobFactory);
return schedulerFactoryBean;
}
}
工厂类 factory.java
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;
@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)