在项目开发中,经常需要编写定时任务来实现一些功能:
-
定时备份数据库、定时发送邮件、定时清理数据、定时提醒或通知、信用卡每月还款提醒
-
未支付的订单15分钟之后自动取消、未确认收货的订单7天之后自动确认收货
定时任务的实现:
-
Spring Task框架:Spring提供的任务调度工具,可以按照约定的时间自动执行特定的任务功能
-
Quartz框架:一个开源的任务调度框架
-
ScheduledThreadPoolExecutor:JDK8提供的定时任务执行
Cron表达式是一个字符串,由7个字段组成,使用空格隔开 ,用于指定定时任务的执行时间。也称为七子表达式
字段 | 取值范围 | 说明 |
---|---|---|
秒 | 0-59 | */10 |
分 | 0-59 | |
时 | 0-23 | 6-16 |
日 | 1-31 | |
月 | 1-12 | |
星期 | 0-7 | 0和7都表示星期日 |
年 | 1970~2099 | 此项非必需,可以省略 |
使用以下特殊字符来指定执行时间:
-
星号(*):表示匹配该字段的所有可能值
-
问号(?):表示不关心该字段具体的值
-
斜线(/):表示指定一个间隔
-
逗号(,):表示列举多个值
-
连字符(-):表示指定一个范围
Cron表达式在线生成器:在线Cron表达式生成器
基本用法
Spring Task的使用步骤:
-
定制任务,使用
@Scheduled
@Component public class MyTask { // @Scheduled(cron = "0/2 * * * * ?") // 每隔2秒执行一次@Scheduled(cron = "0 0 3 * * ?") // 每天凌晨3点执行public void task1() {System.out.println("定时任务1执行了!");} }
-
启用定时任务,使用
@EnableScheduling
@SpringBootApplication @EnableScheduling // 开启定时任务 public class Springboot02QuickApplication { public static void main(String[] args) {SpringApplication.run(Springboot02QuickApplication.class, args);} }