基于spring-boot构建
引入依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
Job中注入service,原生Job并不支持这种方式
public class MySpringQuartzJob extends QuartzJobBean {
@Autowired
private IUserDetailService iUserDetailService;
}
测试
@Component
public class QuartzInit {
@Autowired
public Scheduler scheduler;
@PostConstruct
public void initJob() throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(MySpringQuartzJob.class)
.build();
Trigger trigger = TriggerBuilder.newTrigger().startNow().build();
scheduler.scheduleJob(jobDetail, trigger);
}
}
配置持久化
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:mysql://127.0.0.1:3306/project?characterEncoding=utf-8&userSSL=false
username: root
password: ENC(t4ICoflZQWgNIxg32+fYBQ==)
type: com.alibaba.druid.pool.DruidDataSource
druid:
validation-query: select 1
## quartz定时任务,采用数据库方式
quartz:
job-store-type: jdbc
jdbc:
# 初次启动使用always自动重新创建相应的表
initialize-schema: never
#定时任务启动开关,true-开 false-关,如这台服务器只是添加任务,不跑任务,则设置为false
auto-startup: true
#延迟1秒启动定时任务
startup-delay: 1s
#启动时更新己存在的Job
overwrite-existing-jobs: true
properties:
org:
quartz:
scheduler:
instanceName: MyScheduler
instanceId: AUTO
jobStore:
class: org.springframework.scheduling.quartz.LocalDataSourceJobStore
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# 如果你修改了默认表前缀,则在这里修改
tablePrefix: QRTZ_
isClustered: true
misfireThreshold: 12000
clusterCheckinInterval: 15000
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 5
threadPriority: 5
threadsInheritContextClassLoaderOfInitializingThread: true
部分注解的使用
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class MySpringQuartzJob extends QuartzJobBean implements InterruptableJob
作用在Job类
@DisallowConcurrentExecution
表示如果一个任务需要执行5s,但是我们设置的执行间隔是2s,那么等任务真正执行时,会按照实际执行时间5s串行进行执行
@PersistJobDataAfterExecution
表示我们在一次任务中对一个dataMap数据进行修改,则此次修改的数据对下一次任务执行时生效