SpringTask定时任务的使用
实现定时任务简单的有四种方式:Timer\ScheduledThreadPool线程池\quartz(常用),还有另一种就是springtask。
都说springtask上手简单,于是简单的研究一下springtask的使用,并且运用到自己的项目中。其也有两种配置方式,第一种是基于xml配置,第二种是基于注解。
SprngTask没有专门的包,其核心类位于spring-context包中。所以引入spring的核心包此功能即可使用。
在实际的项目中,我们经常将job作为action层,在job中注入service去操作底层的dao,或者定时的向其他系统拉取数据,再或者向其他系统推送数据。
1.基于xml配置的简单的使用
测试类:(每五秒钟打印一次日志)
package cn.xm.exam.job; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class FirstTestJob {
private static final Logger log = LoggerFactory.getLogger(FirstTestJob.class);
private static int count; public void cron() {
log.info("spring task execute times {}", count++);
}
}
xml配置:(非常类似于quartz的cron表达式和linux定时的cron表达式)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <context:component-scan base-package="cn.xm.exam.job"></context:component-scan> <task:scheduled-tasks>
<task:scheduled ref="firstTestJob" method="cron"
cron="0/5 * * * * ?" />
</task:scheduled-tasks> </beans>
重点是引入task的schema:
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
结果:
...
2018-11-14 22:35:00 [cn.xm.exam.job.FirstTestJob]-[INFO] spring task execute times 59
2018-11-14 22:35:05 [cn.xm.exam.job.FirstTestJob]-[INFO] spring task execute times 60
2018-11-14 22:35:10 [cn.xm.exam.job.FirstTestJob]-[INFO] spring task execute times 61
2018-11-14 22:35:15 [cn.xm.exam.job.FirstTestJob]-[INFO] spring task execute times 62
2018-11-14 22:35:20 [cn.xm.exam.job.FirstTestJob]-[INFO] spring task execute times 63
2018-11-14 22:35:25 [cn.xm.exam.job.FirstTestJob]-[INFO] spring task execute times 64
...
2.基于注解的使用
首先查看注解的源码:
注解使用必须在xml中开启注解任务,使注解生效:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <context:component-scan base-package="cn.xm.exam.job"></context:component-scan> <!-- 开启注解任务 -->
<task:annotation-driven /> </beans>
测试类:(每十秒钟打印一次日志)
package cn.xm.exam.job; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class FirstAnnotationJob {
private static final Logger log = LoggerFactory.getLogger(FirstAnnotationJob.class);
private static int count; @Scheduled(cron = "0/10 * * * * ?")
public void cron() {
log.info("spring anno task execute times {}", count++);
}
}
结果:
2018-11-14 22:44:40 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 0
2018-11-14 22:44:50 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 1
2018-11-14 22:45:00 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 2
2018-11-14 22:45:10 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 3
查看@Scheduled的源码:(位于spring-context包内)
/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. */
package org.springframework.scheduling.annotation; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled { /**
* A cron-like expression, extending the usual UN*X definition to include
* triggers on the second as well as minute, hour, day of month, month
* and day of week. e.g. {@code "0 * * * * MON-FRI"} means once per minute on
* weekdays (at the top of the minute - the 0th second).
* @return an expression that can be parsed to a cron schedule
* @see org.springframework.scheduling.support.CronSequenceGenerator
*/
String cron() default ""; /**
* Execute the annotated method with a fixed period between the end
* of the last invocation and the start of the next.
* @return the delay in milliseconds
*/
long fixedDelay() default -1; /**
* Execute the annotated method with a fixed period between invocations.
* @return the period in milliseconds
*/
long fixedRate() default -1; /**
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate()} or {@link #fixedDelay()} task.
* @return the initial delay in milliseconds
* @since 3.2
*/
long initialDelay() default 0; }
参数解释:(其实源码的注释也写的非常清楚了)
cron:cron表达式
fixedDelay:表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒
fixedRate:从上一个任务开始到下一个任务开始的间隔,单位是毫秒。
initialDelay:任务第一次被调用前的延时,单位毫秒。
需要注意的是上面的前三个属性只能保留一个,不能同时出现,最后一个延时操作可以与上面三个参数搭配。否则会报异常如下:
java.lang.IllegalArgumentException: Exactly one of the 'cron', 'fixedDelay', or 'fixedRate' attributes is required.
接下来我们测试上面的参数:
fixedDelay :方法中模拟处理用了2s
package cn.xm.exam.job; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class FirstAnnotationJob {
private static final Logger log = LoggerFactory.getLogger(FirstAnnotationJob.class);
private static int count; @Scheduled(fixedDelay = 10000)
public void cron() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.error("InterruptedException ", e);
}
log.info("spring anno task execute times {}", count++);
}
}
结果:(实际每两次任务中间相差12s,也就是第一次任务结束10s后开启下次任务)
2018-11-14 23:02:04 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 1
2018-11-14 23:02:16 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 2
2018-11-14 23:02:28 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 3
2018-11-14 23:02:40 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 4
fixedRate测试:
package cn.xm.exam.job; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class FirstAnnotationJob {
private static final Logger log = LoggerFactory.getLogger(FirstAnnotationJob.class);
private static int count; @Scheduled(fixedRate = 10000)
public void cron() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.error("InterruptedException ", e);
}
log.info("spring anno task execute times {}", count++);
}
}
结果:(每两次任务相差10s,也就是本次任务开始之后10s后就开启下次任务,不管中间处理花费多长时间)
2018-11-14 23:04:47 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 1
2018-11-14 23:04:57 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 2
2018-11-14 23:05:07 [cn.xm.exam.job.FirstAnnotationJob]-[INFO] spring anno task execute times 3
至此完成了springtask的测试,确实比quartz简便的多,使用也简单。
附一个在线cron表达式生成器:http://cron.qqe2.com/
SpringTask定时任务的使用的更多相关文章
- SpringTask定时任务实例讲解【Java获取微信公众平台accessToken及jsapiTicket】
项目中调用微信公众平台的接口时,因为获取到的accessToken及jsapiTicket有效时长只有两个小时,需要不断更新. 所以做了个定时任务,记录一下. .SpringTask实现有两种方式,一 ...
- spring学习总结(mybatis,事务,测试JUnit4,日志log4j&slf4j,定时任务quartz&spring-task,jetty,Restful-jersey等)
在实战中学习,模仿博客园的部分功能.包括用户的注册,登陆:发表新随笔,阅读随笔:发表评论,以及定时任务等.Entity层设计3张表,分别为user表(用户),essay表(随笔)以及comment表( ...
- Spring生态研习【一】:定时任务Spring-task
本系列具体研究一下spring生态中的重要或者常用的功能套件,今天从定时任务开始,主要是spring-task.至于quartz,下次找个时间再总结. 我的验证环境,是SpringCloud体系下,基 ...
- 整合SpringTask实现定时任务
一.框架介绍 SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用. 二.Corn表达式 概述 Cron表达式是一个字符串,包括 ...
- springboot使用SpringTask实现定时任务
SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用. 只需要在配置类中添加一个@EnableScheduling注解即可开启S ...
- 使用SpringTask 进行Java定时任务开发
(我这里的案例 是模拟 将项目包放到tomcat里面运行 ) 新建一个Java Web的Maven项目....... 此过程省略... 项目结构如图: 1.pom.xml 配置 <?xml ve ...
- 轻量级Spring定时任务(Spring-task)
Spring3.0以后自主开发的定时任务工具,spring-task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式. ...
- Spring定时任务(一):SpringTask使用
背景:在日常开发中,经常会用到任务调度这类程序.实现方法常用的有:A. 通过java.util.Timer.TimerTask实现. B.通过Spring自带的SpringTask. C. 通过Spr ...
- SpringMVC中定时任务配置
在项目中使用定时任务是常有的事,比如每天定时进行数据同步或者备份等等. 以前在从事C语言开发的时候,定时任务都是通过写个shell脚本,然后添加到linux定时任务中进行调度的. 现在使用Spring ...
随机推荐
- (线段判交的一些注意。。。)nyoj 1016-德莱联盟
1016-德莱联盟 内存限制:64MB 时间限制:1000ms 特判: No通过数:9 提交数:9 难度:1 题目描述: 欢迎来到德莱联盟.... 德莱文... 德莱文在逃跑,卡兹克在追.... 我们 ...
- C++ 二维数组作为形参传递使用实例
在线代码编辑器: http://codepad.org/ 1.*指针 void display(int *arr, const int row, const int col) { ; i < r ...
- Sql Server时间格式化笔记
Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AMSelect CONVERT(varchar(100), GETDATE() ...
- ruby--Hash方法汇总
一.给Hash添加默认值 :h = {1,2,3,4} #=> {1 => 2, 3 => 4} h.default = 7 h[1] ...
- 转---变量LEGB规则
Python 变量作用域的规则是 LEGB LEGB含义解释: L -- Local(function):函数内的名字空间 E -- Enclosing function locals:外部嵌套函数的 ...
- 解析ArcGis的标注(二)——认识ArcGis标注标签
该“标注”系列博文的标注引擎使用“标准标注引擎(standard label engine)”,这个概念如不知道,可不理会,ArcGis默认标注引擎就是它. 本篇的标注语句解析使用VBScript,注 ...
- [Android] Android 使用 Greendao 操作 db sqlite
Android 使用 Greendao 操作 db sqlite GreenDAO是一个开源的安卓ORM框架,能够使SQLite数据库的开发再次变得有趣.它减轻开发人员处理低级数据库需求,同时节省开发 ...
- SpringBoot系列: 使用 flyway 管理数据库版本
Flyway 和 Liquibase 都是 Java 项目中常用的 DB migration 工具, 从使用简便性看,Flyway 比 Liquibase 更简单, 从 github 的 star ...
- [转载]SpringBoot系列: SpringMVC 参数绑定注解解析
本文转载自 https://www.cnblogs.com/morethink/p/8028664.html, 作者写得非常好, 致谢! SpringMVC 参数绑定注解解析 本文介绍了用于参数绑 ...
- Java SSM框架之MyBatis3(十)MyBatis批量插入数据(MySql)
插入成功后返回自增主键 <insert id="insertRole" parameterType="role" useGeneratedKeys=&qu ...