Spring注解@Scheduled执行定时任务
来源:互联网 发布:windows平板救砖 编辑:程序博客网 时间:2024/05/28 11:48
Spring注解@Scheduled执行定时任务
项目的开发中往往需要设置定时任务,比如每天早上6点要及时推送一个消息,又比如每过一分钟要对系统当前用户的行为进行识别等等;在spring中提供了使用@Scheduled的注解形式来执行定时任务。
①在spring的配置文件中导入
xmlns:task="http://www.springframework.org/schema/task xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation=" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
②配置定时任务的线程池
<task:executor id="executor" pool-size="10"/><task:scheduler id="scheduler" pool-size="5"/><task:annotation-driven executor="executor" scheduler="scheduler" />
开启task任务及其相关配置
③扫描任务配置
<context:annotation-config /><context:component-scan base-package="com.abc.service.impl" />
使用的扫描注解方式来实现Spring的定时任务,并指定扫描的包路径
④为定时任务的方法加上注解
@Scheduled(cron = "0/10 * * * * ?")public void a() { logger.info("定时任务a执行了...");}
注: 定时任务不能有返回值;只能在注解了component类中使用定时任务。
上述代码的输出效果为(每隔10秒):
定时任务a执行了...定时任务a执行了...定时任务a执行了...定时任务a执行了...
其中cron为表达式,即设置定时任务的执行时间或者是间隔的表达式。
⑤corn表达式
是用于在注解@Scheduled中设置定时任务执行方式的。
以下是网上摘抄的部分说明:
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。
corn表达式格式:
秒 分 时 日 月 周 年(可选)。
“?”字符:表示不确定的值
“,”字符:指定数个值
“-”字符:指定一个值的范围
“/”字符:指定一个值的增加幅度。n/m表示从n开始,每次增加m
“L”字符:用在日表示一个月中的最后一天,用在周表示该月最后一个星期X
“W”字符:指定离给定日期最近的工作日(周一到周五)
“#”字符:表示该月第几个周X。6#3表示该月第3个周五
例子:
每隔5秒执行一次:/5 * * * ?
每隔1分钟执行一次:0 /1 * * ?
每天23点执行一次:0 0 23 * * ?
每天凌晨1点执行一次:0 0 1 * * ?
每月1号凌晨1点执行一次:0 0 1 1 * ?
每月最后一天23点执行一次:0 0 23 L * ?
每周星期天凌晨1点实行一次:0 0 1 ? * L
在26分、29分、33分执行一次:0 26,29,33 * * * ?
每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?
每天的8点开始,2小时执行一次:0 0 8/2 * * ?
补充:如果在集群的环境下,这种定时任务应注意使用,因为多台机器会各自执行相同的定时任务。解决此问题的思想是:制定一台机器的ip,当触发定时任务的时候进行判断,只识别集群中的一台机器执行定时任务。(具体详见后续博文)
- 使用spring @Scheduled注解执行定时任务、
- 使用spring @Scheduled注解执行定时任务、
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务、
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务、
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务、
- 使用spring @Scheduled 注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- 使用spring @Scheduled注解执行定时任务
- VMware12-Centos7-Oracle12C(三)--完结,接一、二
- parentNode,parentElement,childNodes,children的区别
- 利用python+opencv识别图片中的圆形(霍夫变换)
- AirPower的无线充电板
- amixer命令行修改声音大小
- Spring注解@Scheduled执行定时任务
- boot.img的解包与打包
- Windows10下安装VS2013语言包(Compatibility mode is on兼容模式问题)
- android 回合计时器
- BMS状态转换及上电策略
- Java的九个内置对象和四个作用域
- 免费的内网穿透方法(Ngrok映射端口、不限速、不限流量)
- 皮带线定时器的修改
- sessionStorage 、localStorage 和 cookie 之间的区别