springboot项目在启动时自动添加定时任务
1、springboot项目的启动器类添加注解
@EnableScheduling
2、动态添加定时任务
需求:启动项目时自动添加定时任务,定时时间从数据库查
2-1、添加配置类
新建config包,包下新建ScheduleTask
类实现SchedulingConfigurer
接口,代码如下:
package org.springxxx.modules.xxx.config;
import java.util.List;
import org.springblade.modules.datatrans.entity.DataResource;
import org.springblade.modules.datatrans.mapper.DataResourceMapper;
import org.springblade.modules.datatrans.service.IDataResourceService;
import org.springblade.modules.datatrans.utils.CronExpParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@Configuration // 1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class ScheduleTask implements SchedulingConfigurer {
@Autowired
DataResourceMapper dataResourceMapper;
@Autowired
IDataResourceService dataResourceService;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
QueryWrapper<DataResource> drWrapper = new QueryWrapper<>();
List<DataResource> dataResourceList = dataResourceMapper.selectList(drWrapper.eq("deleted", 0));
for (DataResource dataResource : dataResourceList) {
// 2.1 从数据库获取执行周期
String cron = dataResource.getExecuteCron();
// 2.2 合法性校验. 正确的cron表达式+数据资源可访问状态为正常
if (!StringUtils.isEmpty(cron) && dataResource.getAccessibleState().equals("1")) {
System.out.println("添加动态定时任务: " + dataResource.getDataName() + ","
+ CronExpParser.translateToChinese(cron) + "执行一次");
taskRegistrar.addTriggerTask(
// 1.添加任务内容(Runnable)
() -> {
System.out.println("执行动态定时任务: " + dataResource.getDataName());
dataResourceService.refreshByTime(dataResource);
},
// 2.设置执行周期(Trigger)
triggerContext -> {
// 2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
});
}
}
}
}
3、静态添加定时任务
需求:定时执行某个方法,定时时间写死
在方法上面加
@Scheduled(cron = "0 0/30 * * * ? ")
public static void checkRsa() {
System.out.println("每三十分钟执行一次")
}
4、cron表达式在线生成
5、如果不用cron表达式,可以直接使用毫秒
//initialDelay:当任务启动后多久开始执行此方法,fixedDelay:执行频率为多少
@Scheduled(initialDelay = 1000,fixedDelay = 1000*10)
public static void checkRsa() {
System.out.println("每十秒钟执行一次")
}