使用SpringBoot创建Scheduled定时任务非常简单,目前主要有以下三种创建方式:
一、基于注解(@Scheduled)静态任务
二、基于接口(SchedulingConfigurer),可根据数据库动态调度任务
三、基于注解设定多线程定时任务
静态:基于注解
基于注解@Scheduled默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。
创建定时器
使用SpringBoot基于注解来创建定时任务非常简单,只需几行代码便可完成。
代码如下:
@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class SaticScheduleTask {
//*/10 * * * * ? * 每隔10秒执行一次
//0 30 1 * * ? * 每天凌晨1点30分0秒开始执行
//0 0 10,14,16 * * ? 每天10点、14点、16点执行一次
//0 15 10 L * ? 每个月最后一天的10点15分执行一次
//0 15 10 ? * 6L 2018-2020 2018年到2020年每个月最后一个星期五的10:15执行
//3.添加定时任务
@Scheduled(cron = "0/30 * * * * ?")
//@Scheduled(fixedRate = 1000 * 30L)
private void configureTasks() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String strDate =dateFormat.format(new Date());
System.err.println("执行静态定时任务时间: " + strDate);
}
}
启动应用后,查看控制台打印效果
Cron表达式参数分别表示:
秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
日(0~31)的某天,需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
corn表达式:
“0 0 * * * *” 表示每小时0分0秒执行一次
" */10 * * * * *" 表示每10秒执行一次
“0 0 8-10 * * *” 表示每天8,9,10点执行
“0 0/30 8-10 * * *” 表示每天8点到10点,每半小时执行
“0 0 9-17 * * MON-FRI” 表示每周一至周五,9点到17点的0分0秒执行
“0 0 0 25 12 ?” 表示每年圣诞节(12月25日)0时0分0秒执行
@Scheduled:除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。
使用@Scheduled 很方便,但缺点是当我们调整了执行周期的时候,需要重启应用才能生效,这多少有些不方便。为了达到实时生效的效果,可以使用接口来完成定时任务。
动态:基于接口
基于接口(SchedulingConfigurer)
添加数据库记录:
开启本地数据库mysql,随便打开查询窗口,然后执行以下脚本:
CREATE TABLE `cron` (
`cron_id` varchar(30) NOT NULL PRIMARY KEY,
`cron` varchar(30) NOT NULL
);
INSERT INTO `cron` VALUES ('1', '0/5 * * * * ?');
Mybatis 生成 Mapper.xml 、dao 、model等
增加服务接口及实现
@Service
public interface CronService {
/**
* 生成
* @param Id 自动编码标识ID
* @return
*/
Cron getCronInfoById(String Id);
}
@Service
public class CronServiceImpl implements CronService {
@Autowired
private CronMapper cronMapper;
@Override
public Cron getCronInfoById(String Id) {
return cronMapper.selectByPrimaryKey(Id);
}
}
创建定时器
数据库准备好数据之后,我们编写定时任务,注意这里添加的是TriggerTask,目的是循环读取我们在数据库设置好的执行周期,以及执行相关定时任务的内容。
@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer {
@Autowired //注入mapper
@SuppressWarnings("all")
CronService cronService;
/**
* 执行定时任务.
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar)
{
taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
//2.设置执行周期(Trigger)
triggerContext -> {
//2.1 从数据库获取执行周期
Cron cronInfo = cronService.getCronInfoById("1");
String cron = cronInfo.getCron();
//2.2 合法性校验.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}
启动应用后,查看控制台打印效果
多线程
基于注解设定多线程定时任务
创建多线程定时任务
@Component
@EnableScheduling // 1.开启定时任务
@EnableAsync // 2.开启多线程
public class MultithreadScheduleTask {
@Async
@Scheduled(fixedDelay = 30*1000) //间隔1秒
public void first() throws InterruptedException {
System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
System.out.println();
Thread.sleep(1000 * 10);
}
@Autowired
private UserService userService;
@Async
@Scheduled(fixedRate =60*1000)
public void second() {
System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
User userInfo = userService.getUserInfoById(1);
System.out.println(userInfo.getUserId().toString() + " " + userInfo.getUserAccount());
System.out.println();
}
//*/10 * * * * ? * 每隔10秒执行一次
//0 30 1 * * ? * 每天凌晨1点30分0秒开始执行
//0 0 10,14,16 * * ? 每天10点、14点、16点执行一次
//0 15 10 L * ? 每个月最后一天的10点15分执行一次
//0 15 10 ? * 6L 2018-2020 2018年到2020年每个月最后一个星期五的10:15执行
@Async
@Scheduled(cron = "47 * * * * ?")
public void runCornExpTask(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String strDate =dateFormat.format(new Date());
System.err.println("*之后的自带定时任务实现 ===> cron表示按corn表达式执行该任务---打印当前时间: " + strDate);
}
}
注: 这里的@Async注解很关键,多任务异步执行
启动应用后,查看控制台打印效果