一、SpringTask是什么?
SpringTask是spring框架提供的任务调度框架,定时执行指定方法的Java逻辑代码。
使用场景:
信用卡每月还款提醒
银行贷款每月还款提醒
手机话费不足提醒
入职纪念日为用户发送通知
二、cron表达式
介绍
cron表达式是一个字符串,通过cron表达式可以定义任务触发的时间
构成规则:分为6,7个域,空格隔开,每个域有不同的含义
这些域分别为:秒 分 时 日 月 周 年
cron表达式在线生成器
https://cron.qqe2.com/
三 入门案例
第一步开启任务调度:
通过@EnableSching在启动类上标记来开启任务调度
package com.sky;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@Slf4j
@EnableCaching
@EnableScheduling
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
log.info("server started");
}
}
第二步创建任务类:
创建一个任务类交给spring容器管理,
任务类方法由注解@Scheduled标记方法不能有返回值
package com.sky.task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@Slf4j
public class Task {
@Scheduled(cron = "0/3 * * * * ?")
public void task(){
log.info("当前时间为{}",new Date());
}
}
执行效果
com.sky.task.Task : 当前时间为Sun Jul 09 18:02:45 CST 2023
2023-07-09 18:02:48.003 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:02:48 CST 2023
2023-07-09 18:02:51.001 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:02:51 CST 2023
2023-07-09 18:02:54.004 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:02:54 CST 2023
2023-07-09 18:02:57.009 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:02:57 CST 2023
2023-07-09 18:03:00.006 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:03:00 CST 2023
2023-07-09 18:03:03.002 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:03:03 CST 2023
2023-07-09 18:03:06.001 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:03:06 CST 2023
2023-07-09 18:03:09.003 INFO 18256 --- [ scheduling-1] com.sky.task.Task : 当前时间为Sun Jul 09 18:03:09 CST 2023