三、Quartz基于SpringBoot构建

博客介绍基于Spring Boot的构建过程,包括引入依赖坐标、解决Job中注入service问题并进行测试,还涉及持久化配置。同时讲解了部分注解的使用,如@DisallowConcurrentExecution和@PersistJobDataAfterExecution的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于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数据进行修改,则此次修改的数据对下一次任务执行时生效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值