Spring Boot 定时任务实例分析
2018-03-21 16:03
651 查看
首先使用maven搭建一个Springboot 项目。
添加依赖到pom.xml中
我们都知道,springboot有一个自己的入口,也就是@SpringBootApplication(他是一个组合注解 由@Configuration,@EnableAutoConfiguration和@ComponentScan组成)
定时器需要有一个总开关,因为我可能要定时很多函数,如果我想全都暂时关上总不能一个一个把注解给删掉吧。所以我们需要先把总开关打开,也就是在springboot的入口处添加@EnableScheduling这个注解。
启动工程之后,每隔5秒打印一段时间。
@Scheduled 注解可以接受两种定时的设置,一种是我们常用的cron=”/5 * * * ?” ,一种是 fixedRate=5000,两种都表示每隔五秒打印一下内容。
cron 参数
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为
添加依赖到pom.xml中
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>
我们都知道,springboot有一个自己的入口,也就是@SpringBootApplication(他是一个组合注解 由@Configuration,@EnableAutoConfiguration和@ComponentScan组成)
定时器需要有一个总开关,因为我可能要定时很多函数,如果我想全都暂时关上总不能一个一个把注解给删掉吧。所以我们需要先把总开关打开,也就是在springboot的入口处添加@EnableScheduling这个注解。
启动类开启定时调度器
-Application.java@SpringBootApplication @EnableScheduling //开启定时器 public class SpringbootHelloApplication { public static void main(String[] args) { SpringApplication.run(SpringbootHelloApplication.class, args); } }
创建定时器
SchedulerTaskDemo.javapackage com.teracloud.teops.web.utils; import java.util.Date; import org.slf4j.*; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * * @ClassName: SchedulerTaskDemo * @Description: TODO(这里用一句话描述这个类的作用) * @author dcr * @date 2018年3月21日 * */ @Component public class SchedulerTaskDemo { private final Logger LOG = LoggerFactory.getLogger(getClass()); @Scheduled(cron="*/5 * * * * ?") public void< ad92 /span> dateTask() { LOG.info("SchedulerTaskDemo:" + new Date().toString()); } }
启动工程之后,每隔5秒打印一段时间。
参数说明
@Scheduled 注解@Scheduled 注解可以接受两种定时的设置,一种是我们常用的cron=”/5 * * * ?” ,一种是 fixedRate=5000,两种都表示每隔五秒打印一下内容。
cron 参数
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为
秒(0~59) 分钟(0~59) 小时(0~23) 天(月)(0~31,但是你需要考虑你月的天数) 月(0~11) 天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT) 7.年份(1970-2099)
相关文章推荐
- Spring Boot定时任务实例
- Spring Boot定时任务的使用实例代码
- SpringBoot整合Quartz定时任务 的简单实例 2
- Spring Boot定时任务实例
- Spring Boot配置定时任务(实例)
- SpringBoot整合Quartz定时任务 的简单实例
- Spring Boot : 定时任务(十)
- SpringBoot(十四)_springboot使用内置定时任务Scheduled的使用(一)
- Spring Boot 整合定时调度任务Quartz
- Spring Boot 定时任务的使用
- Spring Boot实战之定时任务
- 玩转SpringBoot - 04 Scheduled 定时任务
- SpringBoot开发详解(十二) -- SpringBoot中执行定时任务
- 【springboot】 springboot集成quartz实现定时任务
- SpringBoot定时任务(Spring Schedule )实现方法
- springboot 执行定时任务
- 在Spring Boot中使用@Scheduled实现定时任务
- 解决Spring定时计划任务重复执行两次(实例被构造两次)问题的方法
- (14)Spring Boot定时任务的使用【从零开始学Spring Boot】
- SpringBoot定时任务升级篇(动态添加修改删除定时任务)