在项目开发中,经常会遇到定时任务的场景,Spring提供了@Scheduled注解,方便进行定时任务的开发。
@Scheduled
@Scheduled注解:任务自动化调度。要使用@Scheduled注解,首先需要在启动类添加@EnableScheduling,启用Spring的计划任务执行功能,这样可以在容器中的任何Spring管理的bean上检测@Scheduled注解,执行计划任务
@Scheduled注解参数
cron参数,这个参数是最经常使用的参数,表示接收一个cron参数,cron它是一个表达式,最多接收7个参数,从左到右分别表示:秒 分 时 天 月 周 年;参数以空格隔开,其中年不是必须参数,可以省略。
| 域 | 是否必填 | 参数范围 | 通配符 |
|---|---|---|---|
| 秒 | 是 | 0-59 | , - * / |
| 分 | 是 | 0-59 | , - * / |
| 时 | 是 | 0-23 | , - * / |
| 日 | 是 | 1-31 | , - * ? / L W |
| 月 | 是 | 1-12 或 JAN-DEC | , - * / |
| 周 | 是 | 1-7 或 SUN-SAT | , - * ? / L # |
| 年 | 否 | 1970-2099 | , - * / |
不太会写cron表达式的小伙伴可以参考一下我之前发的开发常用网址中的cron生成器!
定时任务
package com.lxdsoft.scrap.im.bu.tool;
import com.lxdsoft.scrap.im.bu.service.IImBuNonRoadBlacklistService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*定时任务
*/
@Slf4j
@Service
public class ScheduledTask {
@Autowired
private IImBuNonRoadBlacklistService buNonRoadBlacklistService;
@Transactional(rollbackFor = Exception.class, readOnly = false)
@Scheduled(cron = "0 0 21 * * ? ")//此注解的功能是定时任务
//@Scheduled(initialDelay = 1000, fixedDelay = 60000)
public void execute(){
try {
buNonRoadBlacklistService.selectBlacklist();//调用获取到的JSON数据方法
System.out.println(">>>>>定时任务启动<<<<<");
}catch (Exception ex){
log.error(ex.getMessage(), ex);
}
}
}
获取接口数据保存到数据库
定时任务写好后进行调用接口获取数据保存到数据库,操作如下↓
https://blog.csdn.net/Five297/article/details/125929667?spm=1001.2014.3001.5502
https://blog.csdn.net/Five297/article/details/127093510?spm=1001.2014.3001.5502
1万+




被折叠的 条评论
为什么被折叠?



