在Spring项目中使用@Scheduled注解定义简单定时任务
2016-11-29 10:38
786 查看
如题所示,有时候我们需要在Web项目中配置简单的定时任务,而且因为任务并不复杂不想使用定时调度框架(PS:Quartz、ActiveMQ 、Kafka等),这时就可以考虑使用@Scheduled注解来定义简单的定时任务。其全部配置如下:(1)在Spring的配置文件中添加定时任务相关配置:xml配置的头文件中添加:
xmlns:task="http://www.springframework.org/schema/task"以及在xsi:schemaLocation中添加:
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd[/code]最后添加:<context:component-scan base-package="cn.zifangsky.task" /> <task:executor id="executor" pool-size="5"/> <task:scheduler id="scheduler" pool-size="10"/> <task:annotation-driven executor="executor" scheduler="scheduler"/>
其中,这里首先定义了Spring自动扫描定时任务所在的package,也就是“cn.zifangsky.task”。接着定义了两个线程池以及启用定时任务的扫描机制(2)添加测试任务:package cn.zifangsky.task; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class SimpleSpringTask { /** * 每次任务执行完之后的2s后继续执行 */ @Scheduled(fixedDelay=2000) public void say(){ Date current = new Date(); Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("--------" + format.format(current) + "---------"); } /** * 0秒的时候打印 */ @Scheduled(cron="0 * * * * ?") public void print(){ System.out.println("当前是整分!!!"); } }上面第一个任务定义了每个任务执行完之后的2s之后再次执行,如果需要强制指定每隔多少时间执行一次任务,可以将上面的fixedDelay改成fixedRate,如:/** * 每隔两秒执行一次本方法 */ @Scheduled(fixedRate=2000) public void say(){ Date current = new Date(); Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("--------" + format.format(current) + "---------"); }当然,上面的第二种任务形式类似于Linux下的crontab定时任务,几个参数位分别表示:秒、分钟、小时、天(每月中的天)、月份以及星期注:如果想要了解更多的关于Linux中使用crontab命令的用法可以参考我的这篇文章:https://www.zifangsky.cn/591.html(3)测试:运行这个项目后,最后控制台中的输出如下:
PS:上面图片中的水印是我个人博客的域名,因此还请管理员手下留情不要给我标为“转载文章”,谢谢!!!
相关文章推荐
- 使用spring的@Scheduled注解执行定时任务,启动项目不输出警告
- spring3.2使用@Scheduled注解完成定时任务
- 使用spring3.2 @Scheduled注解 定时任务
- spring注解 @Scheduled(cron = "0 0 1 * * *")的使用来实现定时的执行任务
- spring 第13天 使用@scheduled注解执行定时任务
- Spring之——quartz使用@Scheduled注解执行定时任务
- 二、springboot项目的简单使用之:定时任务
- spring注解 @Scheduled(cron = "0 0 1 * * *")的使用来实现定时的执行任务
- spring 第13天 使用@scheduled注解执行定时任务
- spring 使用@scheduled注解执行定时任务
- Spring中使用注解 @Scheduled执行定时任务
- Spring中使用注解 @Scheduled执行定时任务
- spring3.2 @Scheduled注解 定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务、
- Spring使用注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务