SpringBoot整合定时任务之实现Scheduled注解的过程(一个注解全解决)
一、使用场景
定时任务在开发中还是比较常见的,比如:定时发送邮件,定时发送信息,定时更新资源,定时更新数据等等...
二、准备工作
在Spring Boot程序中不需要引入其他Maven依赖
(因为spring-boot-starter-web传递依赖了spring-context模块)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
三、开始搭建配置配置启动项
配置启动项
package com.wang.test.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling//启动定时任务
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
cron表达式
关于cron表达式,小编这里不做过多介绍,这里是cron生成器,大家可以参考
定时任务方法
package com.wang.test.demo.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component//加载到容器中,可以被发现启动
public class TaskTest {
//cron表达式,来控制定时执行时间,这里是每5秒执行一次本方法,业务逻辑可以进行在此方法内进行书写
@Scheduled(cron = "0/5 * * * * ?")
public void printTimeOne(){
System.out.println("任务一:时间为-->"+System.currentTimeMillis());
}
@Scheduled(cron = "0/6 * * * * ?")
public void printTimeTwo(){
System.out.println("任务二:时间为-->"+System.currentTimeMillis());
}
}
四、结果展示

五、总结
这样就完整了SpringBoot整合定时任务了,一个注解全搞定,非常简洁好懂.
到此这篇关于SpringBoot整合定时任务之实现Scheduled注解的过程(一个注解全解决)的文章就介绍到这了,更多相关SpringBoot整合定时任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot解决Required String parameter xxx is not prese
这篇文章主要介绍了SpringBoot解决Required String parameter xxx is not present问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01
SpringBoot中并发定时任务的实现、动态定时任务的实现(看这一篇就够了)推荐
这篇文章主要介绍了SpringBoot并发定时任务动态定时任务实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-04-04
IDEA2020 1.1中Plugins加载不出来的问题及解决方法
这篇文章主要介绍了IDEA2020 1.1中Plugins加载不出来的问题,本文还给大家提到了IDEA 2020.1.1 找不到程序包和符号的问题,感兴趣的朋友跟随小编一起看看吧2020-06-06


最新评论