一、定时任务
在很多情况下任务并非需要立即执行 , 而是需要往后或定期执行 , 这不可能人工去操作 , 所以定时任务就出现了
Scheduled 参数
@Scheduled(fixedRate=5000): 上⼀次开始执⾏时间点之后 5 秒再执⾏
@Scheduled(fixedDelay=5000): 上⼀次执⾏完毕时间点之后 5 秒再执⾏
@Scheduled(initialDelay=1000, fixedRate=5000): 第⼀次延迟 1 秒后执⾏ , 之后按 fixedRate 的规则 每5 秒执⾏⼀次
@Scheduled(cron="*/5 * * * * *"): 通过 cron 表达式定义规则
1、Scheduled创建定时任务
①、在SpringBoot的启动类类中加⼊ @EnableScheduling 注解,启⽤定时任务的配置
②、创建定时任务实现类
package com.lsy.code;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
//任务类
@Component
@Slf4j
public class Task {
//fixedRate 上一次开始执行时间点之后1秒再执行
@Scheduled(fixedRate = 1000,initialDelay = 5000)
public void test(){
log.warn("现在时间:"+ LocalDateTime.now());
}
}
cron 表达式
cron 表达式是一个字符串 , 以 5 或者 6 个空格隔开 ( 示例中是被 5 个空格隔开 ), 字符串被切割为 6 个或者 7 个域 , 每个域都代表不同的含义
{Seconds} {Minutes} {Hours} {DayofMonth} {Month} {DayofWeek} {Year}
{Seconds} {Minutes} {Hours} {DayofMonth} {Month} {DayofWeek}