Spring的@Scheduled注解定时任务

spring提供了@scheduled注解来实现定时任务
需要注意的几点:
1、spring的@Scheduled注解 ,需要写在实现上、
2、定时器的任务方法不能有返回值(有返回值的场景去google)
3、定时器是单线程的
优点:实现中出现exception或者error没有捕获的情况,并不会导致线程退出,只会导致本次执行中断退出,下一次还会再执行。
缺点:单线程的情况下,如果有多个方法都被注解了,就会排队执行。
例如,存在run(),test()两个方法,都用注解间隔5s执行一次的方式执行,实际执行会是
run()-5s-test()-5s-run(),也就是说两次执行之间间隔了10s;
如果run()方法执行完毕就要8s,则会呈现run()-8s-test()-5s-run()
两次执行间隔了13s

可以通过改配置的方式实现任务并行执行。
xmlns 多加下面的内容

<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  

然后配置pool-size来设定多少并发

<task:scheduler id="myScheduler1" pool-size="2"/>

如上就会有2个线程来执行定时任务了。

springboot中,通过下面注解来引入xml配置文件

@SpringBootApplication
@EnableScheduling
@ImportResource("classpath*:sch.xml")
@Component("MyTest")
public class MyTest{
  ……
}

也可以不用@Scheduled注解,直接用xml配置,一个完整的xml示例

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<task:scheduler id="myScheduler1" />
<task:scheduler id="myScheduler2" />
<task:scheduled-tasks scheduler="myScheduler1">
    <task:scheduled ref="MyTest" method="test1" fixed-delay="2000"/>
    <task:scheduled ref="MyTest" method="test2" fixed-delay="2000"/>
</task:scheduled-tasks>
<task:scheduled-tasks scheduler="myScheduler2">
    <task:scheduled ref="MyTest" method="test3" fixed-delay="5000"/>
</task:scheduled-tasks>
</beans>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,800评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,118评论 6 342
  • 博客原文 徒手翻译spring framework 4.2.3官方文档的第33章,若有翻译不当之处请指正。 定时任...
    rabbitGYK阅读 10,993评论 4 24
  • 不动如山,动如飞瀑!
    Ewalnut阅读 1,135评论 0 0
  • 元旦夜后巴扎聚餐后,艺术家观看音乐人魏猛给大家表演重型死亡金属。后巴扎是扎扎与杨青合开,经营新疆与贵州菜,一年半载...
    陈博无关摄影阅读 2,635评论 0 1

友情链接更多精彩内容