springboot定时器的使用 之 cron fixedRate initialDelay 探究
来源:互联网 发布:故宫博物馆淘宝 编辑:程序博客网 时间:2024/06/05 17:10
最近在工作上遇到了一些需要用到定时器的地方,比如项目中对短信发送次数进行限制,每天最多只能发10条,我在数据库中某个表中,对某号码进行信息发送的次数进行登记,每次发信息之前都来数据库中确认下该号码时候还有剩余次数,如果超过10条就不发送,第二天对数据进行充值,防止别人刷我们的短信.
于是想到了定时器的功能,
Springboot的定时器用起来比SpringMvc的简单太多了,下面我们就来介绍下Springboot的定时器:
第一步:在程序入口添加一个@EnableScheduling注解
第二步:新建一个定时类,定义一个方法来对你想要东西进行定时执行如下,在方法的上面使用注解@Scheduled(xxx):
private static int i = 0; private static int x = 0; private static int y = 0; @Scheduled(cron = "0/20 * * * * ?") public void testCron() { i++; System.out.println("<=============第"+i+"次执行开始=================>"); System.out.println("cron测试 :"+i+"---->"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); System.out.println("<=============第"+i+"次执行结束=================>"); }
@Scheduled(cron = "0/20 * * * * ?")这个表示项目启动后,每隔20秒执行一次,但是我测试过好几次都是会延迟多少秒然后调用一次这个定时器,第二次以后就正常啦,每次都
是20秒后执行.
@Scheduled(fixedRate = 10000) public void testFixedRate() { for (int i = 0;i < 6; i++) { System.out.println("fixedRate测试 :"+i+"---->"+new SimpleDateFormat().format(new Date())); } }
@Scheduled(fixedRate = 10000)这个表示服务在启动的时候会先执行一次,然后再每隔10秒再调用一次,我们看控制台就能看的很清楚啦,
该定时器第一次执行的时间是:2017-10-27 16:40:48 ,而项目也是这个时间启动的,然后再过了15秒又执行了一次,所以说这种写法是在项目启动时,执行一次,然后隔多少秒再执行
@Scheduled(initialDelay = 10000,fixedRate = 15000) public void test() { y++; System.out.println("<=============第"+y+"次执行开始=================>"); System.out.println("fixedRate+initialDelay :y---->"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); System.out.println("<=============第"+y+"次执行结束=================>"); }
这个定时器就是在上一个的基础上加了一个initialDelay = 10000 意思就是在容器启动后,延迟10秒后再执行一次定时器,以后每15秒再执行一次该定时器
阅读全文
0 0
- springboot定时器的使用 之 cron fixedRate initialDelay 探究
- java鬼混笔记:springboot 5、springboot的Scheduled定时器:fixedDelay和fixedRate区别
- spring定时器fixedRate的简述
- Springboot的定时器使用
- SpringMVC使用Cron表达式的定时器
- Spring MVC使用Cron表达式的定时器
- SpringBoot 定时器(动态定时器)的使用
- Spring 定时器之cron
- nrf51822学习之定时器的探究
- 一张图让你秒懂Spring @Scheduled定时任务的fixedRate,fixedDelay,cron执行差异
- spring注解@Scheduled中fixedDelay、fixedRate和cron表达式的区别
- SpringBoot学习记录2------定时器的使用
- SpringBoot学习记录2------定时器的使用
- Springboot中使用定时器
- Spring定时器的Cron表达式
- 关于定时器的cron表达式
- 使用springboot时,@Scheduled定时器遇到的问题
- Quartz的cron表达式 (spring定时器 crontab)
- 预览多张图片
- PYTHON学习,推荐廖雪峰老师的网站
- json数据转换
- R语言image函数报错Error in plot.new() : figure margins too large
- 线性链表
- springboot定时器的使用 之 cron fixedRate initialDelay 探究
- JavaScript中的多维数组与对象
- Git常用命令
- 一个程序员送给大学生弟弟的那些话
- Nginx+Sticky实现负载均衡(1)
- 浅析java内存模型--JMM(Java Memory Model)
- C C++ 全套视频课程收录
- 什么是CDN劫持
- HDU