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 ...
随机推荐
- shell之case
在shell变成中,case语句是if语句的一种扩展,将if中的判断语句,展开,同一个变量,对应多个可能的值时,执行不同的操作.具体句型如下: case "变量" in value ...
- C语言#和##操作符使用方法
1.#操作符 1:#操作符用于预处理阶段,将宏参数转换为字符串,只有宏定义中使用(#define) 使用方法: #define STRING(x) #x printf( ...
- SqlAlchenmy基本使用
#简单查询 print(session.query(User).all()) print(session.query(User.name, User.fullname).all()) print(se ...
- As 400错
8:25 Gradle sync started 8:25 Gradle sync failed: Unable to tunnel through proxy. Proxy returns &quo ...
- 信用评分卡 (part 4 of 7)
python信用评分卡(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_camp ...
- Hbase_02、Hbase的常用的shell命令&Hbase的DDL操作&Hbase的DML操作(转)
阅读目录 前言 一.hbase的shell操作 1.1启动hbase shell 1.2执行hbase shell的帮助文档 1.3退出hbase shell 1.4使用status命令查看hbase ...
- 网络编程基础【day09】:简单socket实例(二)
本节内容 1.概述 2.socket实例 3.总结 一.概述 之前我们只是介绍了soket的概念和一些逻辑图表,下面我们来看看,socket的客户端和服务端到底是怎么用的? 二.socket实例 2. ...
- 关于CURL的初步认识
前言:你知道?这个CURL可以做爬虫的工作但是仅限于小型的爬虫.............. (一) CURL的认识 下面我觉得用图片来展示curl比较直观: 所谓的curl就是客户端访问了服务器1,那 ...
- 【转】Linux C下非特定波特率的配置和使用
https://blog.csdn.net/jinhongdu/article/details/43413071 对于非标准的任意波特率需要用ioctl(fd, TIOCGSERIAL, p)和i ...
- django生产环境启动问题
unavailable modifier requested: 0 环境: nginx+uwsgi+django *** Starting uWSGI 2.0.16 (64bit) on [Wed J ...