springboot定时器
来源:互联网 发布:周易取名软件破解版 编辑:程序博客网 时间:2024/06/13 22:34
在使用spring的时候遇到如下场景:由于业务需要,需要定时更新数据库,比如每隔两个小时更新一次某个字段的状态,无论是什么场景只要是需要定时去执行某种操作都可以使用spring的定时器任务来解决,以下将介绍springboot如何使用定时器任务:
创建定时任务:
@Componentpublic class NoticeTask { private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss"); /** * 每两个小时更新一次过期停水通知状态 * @return */ @Scheduled(fixedRate = 2*60*60*1000) public void refreshNoticeStatus(){ System.out.println(simpleDateFormat.format(new Date())); }}
以上代码中@Component将该类交给spring托管,通过使用@Scheduled注解就定义了一个定时器任务,该任务的执行周期为2小时,spring每两小时会调用一次该方法,fixedRate的单位是毫秒,表示任务执行的周期@Scheduled
还有其他一些用法如@Scheduled(initialDelay=5000, fixedRate=5000)
延迟5秒之后每隔5秒执行一次(注意:springboot框架在启动的时候会直接执行一次定时任务,使用该方法可以避免该情况)
启用定时任务
@SpringBootApplication@EnableSchedulingpublic class ApplicationStart { public static void main(String[] args) { SpringApplication.run(ApplicationStart.class, args); }}
通过在springboot的启动类中添加@EnableScheduling
注解即可启动spring定时器任务配置。运行程序即可看到对应的输出。
阅读全文
0 0
- springboot定时器
- Springboot--定时器
- springboot定时器
- SpringBoot(五)定时器
- Springboot的定时器使用
- 定时器--Spring--SpringBoot
- Springboot中使用定时器
- SpringBoot 定时器(动态定时器)的使用
- SpringBoot集成Quartz实现定时器
- SpringBoot学习-(十九)SpringBoot定时器#Schedule
- SpringBoot学习记录2------定时器的使用
- SpringBoot学习记录2------定时器的使用
- SpringBoot学习-Spring定时器的设置
- SpringBoot学习-简单QuartZ定时器设置
- 关于给springboot添加定时器的两种方式
- 使用springboot时,@Scheduled定时器遇到的问题
- springboot定时器的使用 之 cron fixedRate initialDelay 探究
- java鬼混笔记:springboot 5、springboot的Scheduled定时器:fixedDelay和fixedRate区别
- MongoDB (四):索引
- JAVA MVC
- 利用Eclipse编写minigui的helloworld程序
- Java实现zip压缩多个文件下载
- Mysql添加索引
- springboot定时器
- 美国房产投资前景 业内人士看好二级城市多户住宅投资
- spring boot 整合log4j
- python2 去除 字符串中emoji 符号,去除所有4字节utf8字符
- 卷积神经网络(深度学习)一些问题总结
- 算法之最大子数组
- 利用Eclipse编写minigui的helloworld程序
- 给任何view添加全屏倾斜水印
- JavaScript简单计算器