Spring 定时任务的几种实现

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。

近日项目开发中需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息,借此机会整理了一下定时任务的几种实现方式,由于项目采用spring框架,所以我都将结合spring框架来介绍。

一.分类

  • 从实现的技术上来分类,目前主要有三种技术(或者说有三种产品):

  1. Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少,这篇文章将不做详细介绍。
  2. 使用Quartz,这是一个功能比较强大的的调度器,可以让你的程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂,稍后会详细介绍。
  3. Spring3.0以后自带的task,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,稍后会介绍。
  • 从作业类的继承方式来讲,可以分为两类:

  1. 作业类需要继承自特定的作业类基类,如Quartz中需要继承自org.springframework.scheduling.quartz.QuartzJobBean;java.util.Timer中需要继承自java.util.TimerTask。
  2. 作业类即普通的java类,不需要继承自任何基类。

注:个人推荐使用第二种方式,因为这样所以的类都是普通类,不需要事先区别对待。

 

  • 从任务调度的触发时机来分,这里主要是针对作业使用的触发器,主要有以下两种:

  1. 每隔指定时间则触发一次,在Quartz中对应的触发器为:org.springframework.scheduling.quartz.SimpleTriggerBean
  2. 每到指定时间则触发一次,在Quartz中对应的调度器为:org.springframework.scheduling.quartz.CronTriggerBean

注:并非每种任务都可以使用这两种触发器,如java.util.TimerTask任务就只能使用第一种。Quartz和spring task都可以支持这两种触发条件。

 

二.用法说明

详细介绍每种任务调度工具的使用方式,包括Quartz和spring task两种。

Quartz

第一种,作业类继承自特定的基类:org.springframework.scheduling.quartz.QuartzJobBean。

第一步:定义作业类

Java代码  

  1. import org.quartz.JobExecutionContext;  
  2. import org.quartz.JobExecutionException;  
  3. import org.springframework.scheduling.quartz.QuartzJobBean;  
  4. public class Job1 extends QuartzJobBean {  
  5.   
  6. private int timeout;  
  7. private static int i = 0;  
  8. //调度工厂实例化后,经过timeout时间开始执行调度  
  9. public void setTimeout(int timeout) {  
  10. this.timeout = timeout;  
  11. }  
  12.   
  13. /** 
  14. * 要调度的具体任务 
  15. */  
  16. @Override  
  17. protected void executeInternal(JobExecutionContext context)  
  18. throws JobExecutionException {  
  19.   System.out.println("定时任务执行中…");  
  20. }  
  21. }  

 第二步:spring配置文件中配置作业类JobDetailBean

Xml代码  

  1. <bean name="job1" class="org.springframework.scheduling.quartz.JobDetailBean">  
  2. <property name="jobClass" value="com.gy.Job1" />  
  3. <property name="jobDataAsMap">  
  4. <map>  
  5. <entry key="timeout" value="0" />  
  6. </map>  
  7. </property>  
  8. </bean>  

 说明:org.springframework.scheduling.quartz.JobDetailBean有两个属性,jobClass属性即我们在java代码中定义的任务类,jobDataAsMap属性即该任务类中需要注入的属性值。

第三步:配置作业调度的触发方式(触发器)

Quartz的作业触发器有两种,分别是

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次。

配置方式如下:

Xml代码  

  1. <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
  2. <property name="jobDetail" ref="job1" />  
  3. <property name="startDelay" value="0" /><!-- 调度工厂实例化后,经过0秒开始执行调度 -->  
  4. <property name="repeatInterval" value="2000" /><!-- 每2秒调度一次 -->  
  5. </bean>  

第二种CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等。

配置方式如下:

Xml代码  

  1. <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
  2. <property name="jobDetail" ref="job1" />  
  3. <!—每天12:00运行一次 -->  
  4. <property name="cronExpression" value="0 0 12 * * ?" />  
  5. </bean>  

 关于cronExpression表达式的语法参见附录。

第四步:配置调度工厂 

Xml代码  

  1. <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  2. <property name="triggers">  
  3. <list>  
  4. <ref bean="cronTrigger" />  
  5. </list>  
  6. </property>  
  7. </bean>  

 说明:该参数指定的就是之前配置的触发器的名字。

第五步:启动你的应用即可,即将工程部署至tomcat或其他容器。

 

第二种,作业类不继承特定基类。

Spring能够支持这种方式,归功于两个类:

org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

这两个类分别对应spring支持的两种实现任务调度的方式,即前文提到到java自带的timer task方式和Quartz方式。这里我只写MethodInvokingJobDetailFactoryBean的用法,使用该类的好处是,我们的任务类不再需要继承自任何类,而是普通的pojo。

第一步:编写任务类

Java代码  

  1. public class Job2 {  
  2. public void doJob2() {  
  3. System.out.println("不继承QuartzJobBean方式-调度进行中...");  
  4. }  
  5. }  

 可以看出,这就是一个普通的类,并且有一个方法。

第二步:配置作业类

Xml代码  

  1. <bean id="job2"  
  2. class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  3. <property name="targetObject">  
  4. <bean class="com.gy.Job2" />  
  5. </property>  
  6. <property name="targetMethod" value="doJob2" />  
  7. <property name="concurrent" value="false" /><!-- 作业不并发调度 -->  
  8. </bean>  

 说明:这一步是关键步骤,声明一个MethodInvokingJobDetailFactoryBean,有两个关键属性:targetObject指定任务类,targetMethod指定运行的方法。往下的步骤就与方法一相同了,为了完整,同样贴出。

第三步:配置作业调度的触发方式(触发器)

Quartz的作业触发器有两种,分别是

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次。

配置方式如下:

Xml代码  

  1. <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
  2. <property name="jobDetail" ref="job2" />  
  3. <property name="startDelay" value="0" /><!-- 调度工厂实例化后,经过0秒开始执行调度 -->  
  4. <property name="repeatInterval" value="2000" /><!-- 每2秒调度一次 -->  
  5. </bean>  

 第二种CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等。

配置方式如下:

Xml代码  

  1. <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
  2. <property name="jobDetail" ref="job2" />  
  3. <!—每天12:00运行一次 -->  
  4. <property name="cronExpression" value="0 0 12 * * ?" />  
  5. </bean>  

以上两种调度方式根据实际情况,任选一种即可。

第四步:配置调度工厂 

Xml代码  

  1. <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  2. <property name="triggers">  
  3. <list>  
  4. <ref bean="cronTrigger" />  
  5. </list>  
  6. </property>  
  7. </bean>  

说明:该参数指定的就是之前配置的触发器的名字。

第五步:启动你的应用即可,即将工程部署至tomcat或其他容器。

 

到此,spring中Quartz的基本配置就介绍完了,当然了,使用之前,要导入相应的spring的包与Quartz的包,这些就不消多说了。

其实可以看出Quartz的配置看上去还是挺复杂的,没有办法,因为Quartz其实是个重量级的工具,如果我们只是想简单的执行几个简单的定时任务,有没有更简单的工具,有!

请看我第下文Spring task的介绍。

 

Spring-Task

上节介绍了在Spring 中使用Quartz,本文介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种

形式,下面将分别介绍这两种方式。

第一种:配置文件方式

第一步:编写作业类

即普通的pojo,如下:

Java代码  

  1. import org.springframework.stereotype.Service;  
  2. @Service  
  3. public class TaskJob {  
  4.       
  5.     public void job1() {  
  6.         System.out.println(“任务进行中。。。”);  
  7.     }  
  8. }  

 第二步:在spring配置文件头中添加命名空间及描述

Xml代码  

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:task="http://www.springframework.org/schema/task"   
  3.     。。。。。。  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">  

 第三步:spring配置文件中设置具体的任务

Xml代码  

  1.  <task:scheduled-tasks>   
  2.         <task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>   
  3. </task:scheduled-tasks>  
  4.   
  5. <context:component-scan base-package=" com.gy.mytask " />  

说明:ref参数指定的即任务类,method指定的即需要运行的方法,cron及cronExpression表达式,具体写法这里不介绍了,详情见上篇文章附录。

<context:component-scan base-package="com.gy.mytask" />这个配置不消多说了,spring扫描注解用的。

到这里配置就完成了,是不是很简单。

第二种:使用注解形式

也许我们不想每写一个任务类还要在xml文件中配置下,我们可以使用注解@Scheduled,我们看看源文件中该注解的定义:

Java代码  

  1. @Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Documented  
  4. public @interface Scheduled  
  5. {  
  6.   public abstract String cron();  
  7.   
  8.   public abstract long fixedDelay();  
  9.   
  10.   public abstract long fixedRate();  
  11. }  

 可以看出该注解有三个方法或者叫参数,分别表示的意思是:

cron:指定cron表达式

fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。

fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。

 

下面我来配置一下。

第一步:编写pojo

Java代码  

  1. import org.springframework.scheduling.annotation.Scheduled;    
  2. import org.springframework.stereotype.Component;  
  3.   
  4. @Component(“taskJob”)  
  5. public class TaskJob {  
  6.     @Scheduled(cron = "0 0 3 * * ?")  
  7.     public void job1() {  
  8.         System.out.println(“任务进行中。。。”);  
  9.     }  
  10. }  

 第二步:添加task相关的配置:

Xml代码  

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xmlns:task="http://www.springframework.org/schema/task"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  9.         http://www.springframework.org/schema/context   
  10. http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd  
  11.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  12.         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"  
  13.     default-lazy-init="false">  
  14.   
  15.   
  16.     <context:annotation-config />  
  17.     <!—spring扫描注解的配置   -->  
  18.     <context:component-scan base-package="com.gy.mytask" />  
  19.       
  20. <!—开启这个配置,spring才能识别@Scheduled注解   -->  
  21.     <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
  22.     <task:scheduler id="qbScheduler" pool-size="10"/>  

说明:理论上只需要加上<task:annotation-driven />这句配置就可以了,这些参数都不是必须的。

 

 Ok配置完毕,当然spring task还有很多参数,我就不一一解释了,具体参考xsd文档http://www.springframework.org/schema/task/spring-task-3.0.xsd。

附录:

cronExpression的配置说明,具体使用以及参数请百度google

字段   允许值   允许的特殊字符

秒    0-59    , - * /

分    0-59    , - * /

小时    0-23    , - * /

日期    1-31    , - * ? / L W C

月份    1-12 或者 JAN-DEC    , - * /

星期    1-7 或者 SUN-SAT    , - * ? / L C #

年(可选)    留空, 1970-2099    , - * / 

- 区间  

* 通配符  

? 你不想设置那个字段

下面只例出几个式子

 

 

 CRON表达式详解 见另一页博客:http://blog.csdn.net/jiangyu1013/article/details/54405859

CRON表达式    含义 

"0 0 12 * * ?"    每天中午十二点触发 

"0 15 10 ? * *"    每天早上10:15触发 

"0 15 10 * * ?"    每天早上10:15触发 

"0 15 10 * * ? *"    每天早上10:15触发 

"0 15 10 * * ? 2005"    2005年的每天早上10:15触发 

"0 * 14 * * ?"    每天从下午2点开始到2点59分每分钟一次触发 

"0 0/5 14 * * ?"    每天从下午2点开始到2:55分结束每5分钟一次触发 

"0 0/5 14,18 * * ?"    每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 

"0 0-5 14 * * ?"    每天14:00至14:05每分钟一次触发 

"0 10,44 14 ? 3 WED"    三月的每周三的14:10和14:44触发 

"0 15 10 ? * MON-FRI"    每个周一、周二、周三、周四、周五的10:15触发 

 

转自:http://gong1208.iteye.com/blog/1773177

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/451963.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

trie树(字典树)

trie树学习 学习trie树 转载于:https://www.cnblogs.com/cjoierljl/p/9317023.html

Vue 教程第四篇—— Vue 实例化时基本属性

实例元素 el 实例元素指的是 Vue 实例化时编译的容器元素&#xff0c;或者说是 Vue 作用的元素容器 <div id"app"></div> var vm new Vue({el: #app}) 也可以为实例元素指定其它选择器 <div class"app"></div> var vm new Vue({…

Ubuntu将在明年推出平板及手机系统

4月26日下午消息&#xff0c;知名Linux厂商Canonical今天正式发布Ubuntu 12.04版开源操作系统。Ubuntu中国首席代表于立强透露&#xff0c;针对平板电脑的Ubuntu操作系统将在明年推出。 Ubuntu 12.04版开源操作系统发布 Ubuntu操作系统是一款开源操作系统&#xff0c;主要与OE…

scrapy框架异常--no more duplicates will be shown (see DUPEFILTER_DEBUG to show all duplicates)

解决方法&#xff1a; https://blog.csdn.net/qq_40176258/article/details/86527568 https://blog.csdn.net/weixin_39946931/article/details/88390797 谢谢博主分享&#xff01;

【BZOJ3590】[Snoi2013]Quare 状压DP

题解&#xff1a; 一道比较水的题 但这个测试数据极弱我也不知道我的代码正确性是不是有保证 构成一个边双联通 可以由两个有一个公共点的边双联通或者一个边双加一条链构成 所以我们需要要预处理出所有环 令f[i][j][k]表示起点为i&#xff0c;终点为j&#xff0c;经过点的状态…

java swing简介

UI 组件简介 在开始学习 Swing 之前&#xff0c;必须回答针对真正初学者的一个问题&#xff1a;什么是 UI&#xff1f;初学者的答案是“用户界面”。但是因为本教程的目标是要保证您不再只是个初学者&#xff0c;所以我们需要比这个定义更高级的定义。 所以&#xff0c;我再次…

定时任务 cron 表达式详解

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 &#xff08;Spring定时任务的几种实现&#xff1a;见博客另一页&#xff1a;http://blog.csdn.net/jiangyu1013/article/details/54405…

Android Studio 超级简单的打包生成apk

为什么要打包&#xff1a; apk文件就是一个包&#xff0c;打包就是要生成apk文件&#xff0c;有了apk别人才能安装使用。打包分debug版和release包&#xff0c;通常所说的打包指生成release版的apk&#xff0c;release版的apk会比debug版的小&#xff0c;release版的还会进行混…

推荐16款最棒的Visual Studio插件

Visual Studio是微软公司推出的开发环境&#xff0c;Visual Studio可以用来创建Windows平台下的Windows应用程序和网络应用程序&#xff0c;也可以用来创建网络服务、智能设备应用程序和Office插件。 本文介绍16款最棒的Visual Studio扩展&#xff1a; 1. DevColor Extension…

网络爬虫--22.【CrawlSpider实战】实现微信小程序社区爬虫

文章目录一. CrawlSpider二. CrawlSpider案例1. 目录结构2. wxapp_spider.py3. items.py4. pipelines.py5. settings.py6. start.py三. 重点总结一. CrawlSpider 现实情况下&#xff0c;我们需要对满足某个特定条件的url进行爬取&#xff0c;这时候就可以通过CrawlSpider完成。…

可以生成自动文档的注释

使用/**和*/可以用来自动的生成文档。 这种注释以/**开头&#xff0c;以*/结尾

怎么安装Scrapy框架以及安装时出现的一系列错误(win7 64位 python3 pycharm)

因为要学习爬虫&#xff0c;就打算安装Scrapy框架&#xff0c;以下是我安装该模块的步骤&#xff0c;适合于刚入门的小白&#xff1a; 一、打开pycharm&#xff0c;依次点击File---->setting---->Project----->Project Interpreter&#xff0c;打开后&#xff0c;可以…

illegal to have multiple occurrences of contentType with different values 解决

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 在网上查到说是&#xff1a;“包含页面与被包含页面的page指令里面的contentType不一致&#xff0c;仔细检查两个文件第一行的 page....…

xpath-helper: 谷歌浏览器安装xpath helper 插件

1.下载文件xpath-helper.crx xpath链接&#xff1a;https://pan.baidu.com/s/1dFgzBSd 密码&#xff1a;zwvb&#xff0c;感谢这位网友&#xff0c;我从这拿到了 2.在Google浏览器里边找到这个“扩展程序”选项菜单即可。 3.然后就会进入到扩展插件的界面了,把下载好的离线插件…

网络爬虫--23.动态网页数据抓取

文章目录一. Ajax二. 获取Ajax数据的方式三. seleniumchromedriver获取动态数据四. selenium基本操作一. Ajax 二. 获取Ajax数据的方式 三. seleniumchromedriver获取动态数据 selenium文档&#xff1a;https://selenium-python.readthedocs.io/installation.html 四. sele…

视音频编解码技术及其实现

核心提示&#xff1a;一、视音频编码国际标准化组织及其压缩标准介绍 国际上有两个负责视音频编码的标准化组织&#xff0c;一个是VCEG&#xff08;VideocodeExpertGroup&#xff09;&#xff0c;是国际电信联合会下的视频编码专家组&#xff0c;一个是MPEG&#xff08;MotionP…

什么是NaN

NaN&#xff0c;是Not a Number的缩写。NaN 用于处理计算中出现的错误情况&#xff0c;比如 0.0 除以 0.0 或者求负数的平方根。由上面的表中可以看出&#xff0c;对于单精度浮点数&#xff0c;NaN 表示为指数为 emax 1 128&#xff08;指数域全为 1&#xff09;&#xff0c;…

排序系列【比较排序系列之】直接插入排序

最近在和小伙伴们一起研究排序&#xff0c;排序分好多总&#xff0c;后期会做整体总结&#xff0c;本篇则主要对插入排序进行一个整理。 插入排序&#xff08;insert sorting&#xff09;的算法思想十分简单&#xff0c;就是对待排序的记录逐个进行处理&#xff0c;每个新纪录…

Mysql 无法插入中文,中文乱码解决

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 在计算机中搜索 my.ini文件 找到后打开 &#xff0c;并找到这2行作 如下设置 &#xff1a; default-character-setutf8character-se…