天天看点

【SpringBoot新手篇】SpringBoot优雅开启定时任务定时任务

【SpringBoot新手篇】SpringBoot优雅开启定时任务

  • 定时任务
    • Test
    • 启动类开启基于注解的定时任务
    • cron表达式:

定时任务

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前 一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供

TaskExecutor

TaskScheduler

接口。

两个注解:@EnableScheduling、@Scheduled

Test

写一个定时任务

@Service
public class ScheduledService {

    /**
     * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
     * 0 * * * * MON-FRI
     * 【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
     * 【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
     * 【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
     * 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
     * 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
     */
    // @Scheduled(cron = "0 * * * * MON-SAT")
    //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
    // @Scheduled(cron = "0-4 * * * * MON-SAT")
    @Scheduled(cron = "0/4 * * * * MON-SAT")  //每4秒执行一次
    public void hello() {
        System.out.println("hello ... ");
    }
}
           

启动类开启基于注解的定时任务

@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class Springboot11SchedulerTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot11SchedulerTaskApplication.class,args);
    }
}
           
后台没4秒执行一次hello方法,后台打印hello …

cron表达式:

字段 允许值 允许的特殊字符
0-59 , - * /
0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 , - * /
星期 0-7或SUN-SAT 0,7是SUN , - * ? / L C #
特殊字符 代表含义
, 枚举
- 区间
* 任意
/ 步长
? 日/星期冲突匹配
L 最后
W 工作日
C C 和calendar联系后计算过的值
# 星期,4#2,第2个星期四