spring项目如何使用quartz执行多个定时任务

依赖

<!--   定时器   -->
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
     </dependency>

 

配置文件

package com.sundear.demo;

import com.sundear.Timing.*;
import org.quartz.JobDetail;
 
@Configuration
public class QuartzConfiguration {

    // 配置定时任务1
    @Bean(name = "firstJobDetail")
    public MethodInvokingJobDetailFactoryBean firstJobDetail(TimingByDay timingByDay) {
        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
        // 是否并发执行
        jobDetail.setConcurrent(true);
        // 为需要执行的实体类对应的对象
        jobDetail.setTargetObject(timingByDay);
        // 需要执行的方法
        jobDetail.setTargetMethod("task");
        return jobDetail;
    }

    // 配置触发器1
    @Bean(name = "firstTrigger")
    public CronTriggerFactoryBean firstTrigger(JobDetail firstJobDetail) {
        CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
      trigger.setJobDetail(firstJobDetail);
      // 设置定时时间
        trigger.setCronExpression("0 46 15 * * ? 2020");
        return trigger;
    }

    // 配置定时任务2
    @Bean(name = "secondJobDetail")
    public MethodInvokingJobDetailFactoryBean secondJobDetail(TimingByWeek timingByWeek) {
        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
        // 是否并发执行
        jobDetail.setConcurrent(true);
        // 为需要执行的实体类对应的对象
        jobDetail.setTargetObject(timingByWeek);
        // 需要执行的方法
        jobDetail.setTargetMethod("task");
        return jobDetail;
    }

    // 配置触发器2
    @Bean(name = "secondTrigger")
    public CronTriggerFactoryBean secondTrigger(JobDetail secondJobDetail) {
        CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
        trigger.setJobDetail(secondJobDetail);
        trigger.setCronExpression("0 24 19 * * ? 2020");
        return trigger;
    }

    // 配置Scheduler
    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactory
    (Trigger firstTrigger, Trigger secondTrigger,Trigger thirdTrigger,
     Trigger forthTrigger,Trigger fifthTrigger) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        // 延时启动,应用启动5秒后
        bean.setStartupDelay(5);
        // 注册触发器
        bean.setTriggers(firstTrigger,secondTrigger,thirdTrigger);
        return bean;
    }
}

把定时任务绑定在对应的代码上

@Component
@EnableScheduling

public class TimingByDay {

//要定时执行的代码

}

@Component
@EnableScheduling

public class TimingByWeek {

//要定时执行的代码

}

springboot项目启动类需要加上 @EnableScheduling,启动定时任务

posted @ 2020-07-24 16:43  下饭  阅读(1157)  评论(0编辑  收藏  举报