使用Spring Task完成定时任务

1. 前言
上一篇我们学习了Quartz作为定时任务的框架的使用, 这一篇我们来学习Spring全家桶的SpringTask, 对于主张简单易用的Spring家族来说, SpringTask无疑也是一个轻量级的框架,他比Quartz更容易上手.

2. pom.xml依赖
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
  </dependencies>
 
对的,一个spring-context就是他所需要的框架了, 也就是说, 如果你现在开发的项目是用的spring ,无需管依赖,直接看下一步就可以了.

2. 实现代码
spring 的老套路, 一般都可以用两种方式实现: 一是配置方式,二是注解方式

2.1 基于xml配置文件的方式
1 . 写一个运行任务的job类

package com.zgd.spring.task;

import java.util.Date;

/**
 * xml配置方式的定时任务
 */
public class XmlTask {

    /**
     * 要执行的任务
     */
    public void task(){
        System.out.println("定时任务执行中: "+new Date().toLocaleString());
    }
}
 
2 .在resource文件夹中, 创建spring 的配置文件: spring.xml , 这里特意要注意beans中的命名空间不能少

<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"
       xmlns:context="http://www.springframework.org/schema/context"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">

<bean id="xmlTask" class="com.zgd.spring.task.XmlTask"/>
    <task:scheduled-tasks>
        <!--每5秒钟运行一次-->
        <task:scheduled ref="xmlTask" method="task" cron="0/5 * * * * ?"/>
    </task:scheduled-tasks>
</beans>
 
关于cron的语法: 
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:

(1)Seconds  Minutes  Hours  DayofMonth  Month  DayofWeek  Year
(2)Seconds  Minutes  Hours  DayofMonth  Month  DayofWeek

每一个域可出现的字符如下: 
Seconds:可出现", - * /"四个字符,有效范围为0-59的整数 
Minutes:可出现", - * /"四个字符,有效范围为0-59的整数 
Hours:可出现", - * /"四个字符,有效范围为0-23的整数 
DayofMonth:可出现", - * / ? L W C"八个字符,有效范围为1-31的整数 
Month:可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc    
DayofWeek:可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推 
Year:可出现", - * /"四个字符,有效范围为1970-2099年
每一个域都使用数字,但还可以出现如下特殊字符,它们的含义是: 
(1)*:表示匹配该域的任意值,假如在Minutes域使用*, 即表示每分钟都会触发事件。
(2)?:只能用在DayofMonth和DayofWeek两个域。它也匹配域的任意值,但实际不会。因为DayofMonth和 DayofWeek会相互影响。例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法: 13 13 15 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期几都会触发,实际上并不是这样。 
(3)-:表示范围,例如在Minutes域使用5-20,表示从5分到20分钟每分钟触发一次 
(4)/:表示起始时间开始触发,然后每隔固定时间触发一次,例如在Minutes域使用5/20,则意味着5分钟触发一次,而25,45等分别触发一次. 
(5),:表示列出枚举值值。例如:在Minutes域使用5,20,则意味着在5和20分每分钟触发一次。 
(6)L:表示最后,只能出现在DayofWeek和DayofMonth域,如果在DayofWeek域使用5L,意味着在最后的一个星期四触发。 
(7)W: 表示有效工作日(周一到周五),只能出现在DayofMonth域,系统将在离指定日期的最近的有效工作日触发事件。例如:在 DayofMonth使用5W,如果5日是星期六,则将在最近的工作日:星期五,即4日触发。如果5日是星期天,则在6日(周一)触发;如果5日在星期一 到星期五中的一天,则就在5日触发。另外一点,W的最近寻找不会跨过月份 
(8)LW:这两个字符可以连用,表示在某个月最后一个工作日,即最后一个星期五。 
(9)#:用于确定每个月第几个星期几,只能出现在DayofMonth域。例如在4#2,表示某月的第二个星期三。
 
举例如下:

 <!-- 每半分钟触发任务 -->
 <task:scheduled ref="app" method="execute1" cron="30 * * * * ?"/>
 <!-- 每小时的10分30秒触发任务 -->
 <task:scheduled ref="app" method="execute2" cron="30 10 * * * ?"/>
 <!-- 每天1点10分30秒触发任务 -->
 <task:scheduled ref="app" method="execute3" cron="30 10 1 * * ?"/>
 <!-- 每月20号的1点10分30秒触发任务 -->
 <task:scheduled ref="app" method="execute4" cron="30 10 1 20 * ?"/>
 <!-- 每年10月20号的1点10分30秒触发任务 -->
 <task:scheduled ref="app" method="execute5" cron="30 10 1 20 10 ?"/>
 <!-- 每15秒、30秒、45秒时触发任务 -->
 <task:scheduled ref="app" method="execute6" cron="15,30,45 * * * * ?"/>
 <!-- 15秒到45秒每隔1秒触发任务 -->
 <task:scheduled ref="app" method="execute7" cron="15-45 * * * * ?"/>
 <!-- 每分钟的每15秒时任务任务,每隔5秒触发一次 -->
 <task:scheduled ref="app" method="execute8" cron="15/5 * * * * ?"/>
 <!-- 每分钟的15到30秒之间开始触发,每隔5秒触发一次 -->
 <task:scheduled ref="app" method="execute9" cron="15-30/5 * * * * ?"/>
 <!-- 每小时的0分0秒开始触发,每隔3分钟触发一次 -->
 <task:scheduled ref="app" method="execute10" cron="0 0/3 * * * ?"/>
 <!-- 星期一到星期五的10点15分0秒触发任务 -->
 <task:scheduled ref="app" method="execute11" cron="0 15 10 ? * MON-FRI"/>
 
然后我们需要一个测试类来测试:

package com.zgd.spring;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class App{

    @Test
    public void start(){
        System.out.println("启动spring");
        while (true){
            //使用死循环确保程序持续的运行
        }
    }

}
 
运行结果: 


2.2 基于@Scheduled注解的方式
这个注解可以传五个参数:

cron:指定cron表达式
zone:官方文档解释:A time zone for which the cron expression will be resolved。指定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.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。
initialDelay:官方文档解释:Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.任务第一次被调用前的延时,单位毫秒 
再写一个任务类:
package com.zgd.spring.task;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 注解执行的任务
 */
@Component
public class AnnoTask {

    /**
     * 使用注解,5秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void task(){
        System.out.println("注解的方式的任务执行了" + new Date().toLocaleString());
    }

}

 
2 . 在spring配置文件头中添加命名空间及描述,并开启定时任务注解驱动

<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"
       xmlns:context="http://www.springframework.org/schema/context"
       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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="xmlTask" class="com.zgd.spring.task.XmlTask"/>

   <!-- <task:scheduled-tasks>
        &lt;!&ndash;每5秒钟运行一次&ndash;&gt;
        <task:scheduled ref="xmlTask" method="task" cron="0/5 * * * * ?"/>
    </task:scheduled-tasks>-->
    <task:annotation-driven />

    <context:component-scan base-package="com.zgd.spring.task"/>

</beans>
 
这里我试了一下,怎么都无法执行定时任务, 后面仔细检查,发现是没有加上注解的自动扫描, 平时开发肯定都会加上这个,但是由于是测试demo所以把这个忘记了. 
<context:component-scan base-package="com.zgd.spring.task"/>

运行我们的测试类, 结果如下 

--------------------- 
作者:zzzgd_666 
来源:CSDN 
原文:https://blog.csdn.net/zzzgd_666/article/details/80723654 
版权声明:本文为博主原创文章,转载请附上博文链接!

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

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

相关文章

python 读写文件

https://www.cnblogs.com/evablogs/p/6725242.html 文件的打开读写关闭&#xff08;文件使用完毕后必须关闭&#xff0c;因为文件对象会占用操作系统的资源&#xff09; 123456789#写文件with open(rD:\Test\1.txt,w) as f: #with比<strong>try....finally<…

RUNOOB python练习题29

用来练手的python练习题其29&#xff0c;原题链接:python练习实例29 题干 : 给一个不多于5位的正整数&#xff0c;要求&#xff1a;一、求它是几位数&#xff0c;二、逆序打印出各位数字。 实际这个正整数无论位数&#xff0c;在python3中都很容易实现。源代码如下: def ent…

定时任务(Spring Cloud Task)

引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.sprin…

P3357 最长k可重线段集问题 网络流

P3357 最长k可重线段集问题 题目描述 给定平面 x-O-yx−O−y 上 nn 个开线段组成的集合 II&#xff0c;和一个正整数 kk 。试设计一个算法&#xff0c;从开线段集合 II 中选取出开线段集合 S\subseteq IS⊆I ,使得在 xx 轴上的任何一点 pp&#xff0c;SS 中与直线 xpxp 相交的开…

服务被人当肉鸡了,叫一路赚钱 xig

网上看了一下&#xff0c;说有专门人研究服务 个人怀疑是阿里云内部人干的&#xff0c;因为买了服务器后&#xff0c;没有安装对外使用的地址性质的网站&#xff0c;IP开通了之后只有阿里的人知道&#xff0c;上面还有阿里云盾。 看了下进程地址&#xff0c;上面的启动命令 x…

RUNOOB python练习题30 回文数

用来练手的python练习题 30。原题链接:python练习实例30 题干 : 一个5位数&#xff0c;判断它是不是回文数。即12321是回文数&#xff0c;个位与万位相同&#xff0c;十位与千位相同。 与上一个例题类似&#xff0c;判断一个数是不是回文数&#xff0c;我们使用字符串类型更加…

高并发与负载均衡-keepalived-概念介绍

keepalived是用户空间的程序&#xff0c;这个程序会同时在主的lvs和备用的lvs启动 转载于:https://www.cnblogs.com/LXL616/p/10793790.html

asp.net2.0跨域问题

什么叫跨域&#xff1f; 简单理解就是不同服务器&#xff0c;不同域名之间的访问。 1 如何设置asp.net web程序的跨域&#xff1f; 在web.config中添加如下代码 1 <system.webServer> <httpProtocol> <customHeaders> <add name&qu…

RUNOOB python练习题31 根据已输入的字符判断星期几

用来练手的python练习题31&#xff0c; 原题链接 : python练习实例31 题干 : 请输入星期几的第一个字母来判断一下是星期几&#xff0c;如果第一个字母一样&#xff0c;则继续判断第二个字母。 一个条件语句练习题&#xff0c;非常简单了可以说&#xff0c;就是把所有的条件都…

解决FTPClient上传文件为空,显示0字节

JAVA使用FTPClient上传文件时总是为空&#xff0c;而使用FileZilla客户端时却不会。 后来查了下资料&#xff0c;FTP服务器有被动模式和主动模式。&#xff08;具体查另外资料&#xff09; 在JAVA中将FTPClient设置为被动模式即可解决问题。 import org.apache.commons.net.f…

软件工程——结对编程第二次作业

目录 1. 题目及要求2. 功能的设计3. GUI&#xff08;图形用户界面&#xff09;的设计4. 容错机制的设计4.1 选择运算符的容错处理4.2 最大值和题目数输入的容错处理4.3 打开文件容错处理4.4 打印的容错处理5. 程序的运行效果6. 对领航员的评价7. 总结本次作业所开发的程序已上传…

RUNOOB python练习题 32 列表的中括号符号小tips

用来练手的python练习题&#xff0c;原题链接: python练习实例32 题干: 按相反的顺序输出列表的值 拿到题目首先写下如下代码: a [1,2,3,4] for i in range(len(a)):print(a[len(a)-i-1])输出结果如下: 使用一个简单的循环就可以完成这个操作。但其实python有利用中括号操…

redis启动后出现WARNING you have Transparent Huge Pages (THP) support enabled in your kernel问题...

问题描述&#xff1a;启动redis后出现&#xff1a;WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command echo never > /sys/kernel/mm/trans…

Anaconda安装第三方包(whl文件)

先说下环境 Anaconda 对应Python3.5的版本 win7,64位系统。 step1&#xff1a;下载whl文件 step2&#xff1a;打开‘Anaconda Command Prompt‘&#xff0c; 如下图&#xff1a; step3&#xff1a;命令行窗口pip安装&#xff0c;代码如下&#xff1a; pip install 路径whl…

RUNOOB python练习题33 使用join方法实现用逗号分隔列表

用来练手的python练习题&#xff0c;原题链接:python练习实例33 题干: 按逗号分隔列表 用逗号分隔列表&#xff0c;我们就想到了join方法。 str.join(sequence)可以用自定的str字符串分隔一个序列&#xff0c;这个序列可以是字符串&#xff0c;列表&#xff0c;元组&#xff…

Use Vim as a Python IDE

Use Vim as a Python IDE I love vim and often use it to write Python code. Here are some useful plugins and tools for building a delightful vim python environment, escpecially for Vim8: 我喜欢vim&#xff0c;经常用它来编写Python代码。以下是一些有用的插件和工…

sql2008“备份集中的数据库备份与现有的xx数据库不同”解决方法 因为是在另一台电脑对同名数据库做的备份,用常规方法还原,提示不是相同数据库,不让还原,在网上找到下面的方法解决了: 一、右击系

sql2008“备份集中的数据库备份与现有的xx数据库不同”解决方法 因为是在另一台电脑对同名数据库做的备份&#xff0c;用常规方法还原&#xff0c;提示不是相同数据库&#xff0c;不让还原&#xff0c;在网上找到下面的方法解决了&#xff1a; 一、右击系统数据库master&…

RUNOOB python练习题 35 python print各色字体及背景

用来练手的python练习题&#xff0c;原题链接: python练习实例35 题干: 文本颜色设置 python中通过指令可以控制输出的背景颜色&#xff0c;前景颜色&#xff0c;以及显示方式。指令的语法如下: ’\033[显示方式&#xff1b;前景色&#xff1b;背景色m 输出字符 \033[0m’ 其…

ubuntu18.04 qemu环境搭建【学习笔记】

一、准备工具   1.1 安装相关工具     sudo apt-get install qemu libncurses5-dev gcc-arm-linux-gnueabi build-essential 1.2 下载kernel(linux-4.0)与busybox(1.24)源码 https://mirrors.edge.kernel.org/pub/linux/kernel/v4.x/ https://busybox.net/downloads/busy…

for else语句小tips : RUNOOB python练习题36

用来练手的python练习题&#xff0c;原题链接: python练习实例36 题干: 求100之内的素数 求某个范围内的素数&#xff0c;和之前的一个例题其实是一样的&#xff0c;上次的同类例题链接如下: python练习实例12 在实现题目要求时&#xff0c;这次用了for else语句&#xff0c…