Spring Boot定时器创建及使用解析
创建定时器
因为项目需要定时在后端执行任务刷新数据,不需要从前端调用接口,所以需要使用定时器。基于注解方式@Scheduled默认为单线程。
package com.ruanshuai.demo.util;import com.ruanshuai.demo.config.ConfigConsts;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/** * @author ruanshuai * @date 2019/10/30 */@Component@EnableSchedulingpublic class TestSchedule { @Scheduled(fixedDelay = ConfigConsts.TEN_SECONDS) public void test(){ System.out.println('定时任务执行开始!'); System.out.println('这是一个定时任务!'); System.out.println('定时任务执行结束!'); }}
其中TEN_SECONDS表示10秒,定时器任务每10秒钟自动执行一个。
各种时间表示如下:
1 * 1000表示1秒; 60 * 1 * 1000表示1分钟; 60 * 60 * 1 * 1000表示1小时; 24 * 60 * 60 * 1 * 1000表示1天;依此类推
package com.ruanshuai.demo.config;/** * @author ruanshuai * @date 2019/10/30 */public class ConfigConsts { public static final long TEN_SECONDS = 10 * 1 * 1000;}
启动测试
启动项目,定时器任务在项目启动时执行一次,之后每隔10秒自动执行一次。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章:
1. 解决spring @ControllerAdvice处理异常无法正确匹配自定义异常2. IntelliJ IDEA设置自动提示功能快捷键的方法3. IDEA一键完成格式化、去除无用引用、编译的操作4. 从Python的字符串中剥离所有非数字字符(“。”除外)5. python新手学习使用库6. python 网页解析器掌握第三方 lxml 扩展库与 xpath 的使用方法7. SpringBoot整合Redis的步骤8. PHP程序员简单的开展服务治理架构操作详解(二)9. ASP.NET MVC使用jQuery ui的progressbar实现进度条10. android H5本地缓存加载优化的实战

网公网安备