springboot集成定时任务

两种方法

一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方框架 Quartz ,Spring Boot 源自 Spring+SpringMVC ,因此天然具备这两个 Spring 中的定时任务实现策略,当然也支持 Quartz。

一:实现@Scheduled 注解

Scheduled 注解实现比较简单

分为两种方式

1.静态执行

支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
/**
* @Description: [静态定时任务]
* @Param:
* @return:
* @Author: zhanchenlei
* @Date: 2021/5/7
*/
/*
Cron表达式参数分别表示:
秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
月的某天(0~31) 需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
 */
@Configuration //交给spring管理相当于Component的效果
@EnableScheduling // 开启定时任务
public class SimpleScheduleConfig {
    //规定定时时间
    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks() {
        System.err.println("执行定时任务1: " + LocalDateTime.now());
        // TODO: 2021/5/7 需要执行的任务;
    }
}

执行效果图

spring定时任务原理详解 spring自带的定时任务_定时任务

2.动态定时任务

使用数据库存储定时的时间周期,动态管理

步骤:
  • 在库中创建周期表,可以存入corn表达式
  • 集成你所需要数据库
  • 创建定时器
  • 这里添加的是TriggerTask,目的是循环读取我们在数据库设置好的执行周期,以及执行相关定时任务的内容
@Configuration
@EnableScheduling
public class CompleteScheduleConfig implements SchedulingConfigurer {
@Mapper
public interface CronMapper {
    @Select("select cron from cron limit 1")
    String getCron();
}
@Autowired
@SuppressWarnings("all")//引用注解给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默
CronMapper cronMapper;
 
/**
 * 执行定时任务.
 */
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.addTriggerTask(
        //使用lambda表达式
            //你所需要执行的任务·
            () -> System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime()),
            //执行任务的周期,从数据库中获取
            triggerContext -> {
    
                String cron = cronMapper.getCron();
                //判断取出的corn表达式是否为空
                if (StringUtils.isEmpty(cron)) {
                    // Omitted Code ..
                }
                //2.3 返回执行周期(Date)
                return new CronTrigger(cron).nextExecutionTime(triggerContext);
            }
    );
}
}

二:整合Quartz 框架

1.添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

2.启动类添加注解开启定时任务

EnableScheduling开启定时任务

@SpringBootApplication
@EnableScheduling
public class A {
}

3.创建定时任务类

@Component//交给spring容器管理
public class SchedulerTask {

    private int count = 0;

    /**
     * @Description 设置没6秒执行一次
     **/
    @Scheduled(cron = "*/6 * * * * ?")
    private void process(){
        System.out.println("this is scheduler task running " + (count++));
    }

}


//

@Component
public class SchedulerTask2 {
    
    private static final SimpleDateFormat dateFormat =
            new SimpleDateFormat("HH:mm:ss");
    
    /*
    fixedRate说明

@Scheduled(fixedRate = 6000):上一次开始执行时间点之后 6 秒再执行。
@Scheduled(fixedDelay = 6000):上一次执行完毕时间点之后 6 秒再执行。
@Scheduled(initialDelay=1000, fixedRate=6000):第一次延迟 1 秒后执行,之后按 fixedRate 的规则每 6 秒执行一次。
     */
    @Scheduled(fixedRate = 6000)
    private void process(){
        System.out.println("now time is " + dateFormat.format(new Date()));
    }
    
}
*/
@Scheduled(fixedRate = 6000)
private void process(){
    System.out.println("now time is " + dateFormat.format(new Date()));
}

}

Quartz 在使用过程中,有两个关键概念,一个是JobDetail(要做的事情),另一个是触发器(什么时候做),要定义 JobDetail,需要先定义 Job