【WEEK15】 【DAY3】定时任务【中文版】

2024.6.5 Wednesday
接上文【WEEK15】 【DAY2】【DAY3】邮件任务【中文版】

17.异步、定时、邮件任务

17.3.定时任务

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口。(详见TaskExecutor.class和TaskScheduler.class)

  • TaskExecutor接口(任务执行者)
  • TaskScheduler接口(任务调度者)

17.3.1.两个注解:

  • @EnableScheduling——开启定时功能的注解
  • @Scheduled——什么时候执行

17.3.2.Cron表达式

cron表达式:

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

17.3.3.修改Springboot09TestApplication.java开启定时功能的注解

package com.P51;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;


@EnableAsync   //开启异步注解功能

@EnableScheduling  //开启定时功能的注解

@SpringBootApplication
public class Springboot09TestApplication {

   public static void main(String[] args) {
      SpringApplication.run(Springboot09TestApplication.class, args);
   }

}

17.3.4.新建ScheduledService.java

package com.P51.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
    //cron表达式(可以上网搜索表达式等解释)
    @Scheduled(cron = "30 06 14 * * ?") //每天14:06:30执行一次
    @Scheduled(cron = "0/2 * * * * ?")  //每天每两秒执行一次
    public void hello(){
        System.out.println("execute");
    }
}

官方的解释,很详细,值得看:
在这里插入图片描述
在这里插入图片描述

其他参考资料:
https://www.bejson.com/othertools/cron/
在这里插入图片描述

17.3.5.重启项目

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值