Java定时任务(一):spring task

spring task是spring 3.0以后推出的定时器类,可以把它当做一个轻量级的quartz。由于配置简单,功能齐全,在实际项目中经常会用到。spring task支持xml配置、注解配置、java配置三种方式。

方式一:xml配置

1. 定义任务类

package com.sawyer.job;
import java.util.Date;

public class TaskTest {
    public void run() {
        System.out.println(new Date() + " and current thread is " + Thread.currentThread().getName());
    }
}

2. 在xml中声明bean

<?xml version="1.0" encoding="UTF-8"?>
<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"
       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.xsd">

    <!-- task -->
    <bean id="taskTest" class="com.sawyer.job.TaskTest"/>
    <task:scheduled-tasks>
        <task:scheduled ref="taskTest" method="run" cron="0/5 * * * * ?" />
    </task:scheduled-tasks>
</beans>

3. 运行结果

Tue Jul 18 15:22:40 CST 2017 and current thread is scheduler-1
Tue Jul 18 15:22:45 CST 2017 and current thread is scheduler-1
Tue Jul 18 15:22:50 CST 2017 and current thread is scheduler-2
Tue Jul 18 15:22:55 CST 2017 and current thread is scheduler-1
Tue Jul 18 15:23:00 CST 2017 and current thread is scheduler-3
Tue Jul 18 15:23:05 CST 2017 and current thread is scheduler-2
Tue Jul 18 15:23:10 CST 2017 and current thread is scheduler-4
Tue Jul 18 15:23:15 CST 2017 and current thread is scheduler-1
Tue Jul 18 15:23:20 CST 2017 and current thread is scheduler-5
Tue Jul 18 15:23:25 CST 2017 and current thread is scheduler-3
Tue Jul 18 15:23:30 CST 2017 and current thread is scheduler-3

4. 参数说明

  • scheduled-tasks中可以定义多个task,这里指定了一个task,上图中 ref 指定任务类,method指定执行方法,cron指定频率,这里表示每隔5秒执行一下。
  • task中用于指定时间频率的方式,有以下几种:
    cron:cron表达式十分强大,可以指定秒、分、时、日期、月份、星期几,格式为 * * * * * ?
    fixed-rate:单位毫秒,每隔指定时间就执行一次
    fixed-delay:单位毫秒,上次任务执行完后,间隔指定时间后执行下次任务
    initial-delay:单位毫秒,首次执行任务的时候,延迟指定时间执行。
  • spring task 默认使用的是同步模式,即上次任务执行完后,才会执行下次任务。上述时间频率只有在非同步模式下才会完全符合,在同步模式下,实际计算方式为:
    fixed-rate :任务的实际执行时间+fixedRate时间之后,执行下次任务
    fixed-delay:任务的实际执行时间如果小于fixedDelay,则时间间隔为fixedDelay;如果任务的实际执行时间大于fixedDelay,则上次任务执行完后,立即执行下一次任务。

5. 由于上述原因,实际开发的时候都会为spring task 设置线程池。设置线程池的方式,我会在注解配置中说明,而注解配置也是目前最为推荐的一种。


方式二:注解配置

1. 定义任务类

package com.sawyer.job;

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

import java.util.Date;

@Component
public class TaskTest {

    @Scheduled(cron = "0/2 * * * * ?")
    @Async("executor")
    public void run() {
        System.out.println(new Date() + " and current thread is " + Thread.currentThread().getName());
        try {
            Thread.sleep(100000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2. 声明 bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <!-- task -->
    <context:component-scan base-package="com.sawyer.job"/>
    <task:executor id="executor" pool-size="10-15" queue-capacity="10" keep-alive="30000" rejection-policy="DISCARD"/>
    <task:scheduler id="scheduler" pool-size="10"/>
    <task:annotation-driven executor="executor" scheduler="scheduler"/>
</beans>

3. 参数说明

  • 使用@Async开启异步模式,@Async的值为执行器executor,名字需要与xml中配置的一致。
  • executor用于配置线程池
  • pool-size:线程池数量,可以设置范围,也可以设置指定值,最小值为1,最大值为Integer.MAX_VALUE。
  • queue-capacity:任务队列,当线程数达到最小值时,新任务将会被放到队列中。当队列被占满时,executor就会在线程池中创建新的线程,执行新的任务。
  • keep-alive:pool-size的最小值是指核心线程的数量,超过这个数的其他线程,当执行完任务后,可以存活keep-alive指定的时间,单位毫秒。
  • rejection-policy:当线程数达到最大值时,系统的处理策略,可以设置4种方式:
    ABOAT:默认值,抛出异常,不再执行新的任务,直到有空闲线程可以使用
    DISCARD:不抛出异常,不再执行新的任务,知道有空闲线程可以使用
    CALLER_RUNS:在当前线程中执行新的任务
    DISCARD_OLDEST:丢弃最旧的一个任务,空出线程执行新的任务

动态修改时间

在实际的生产环境中,有可能需要动态的修改任务的时间频率,在spring task中只需要实现SchedulingConfigurer接口即可

package com.sawyer.job;

import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
public class TestTask implements SchedulingConfigurer {

    private String cron = "0/3 * * * * ?";
    private int i = 0;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() -> {
            i++;
            System.out.println("Now is " + new Date()+" and the thread is "+Thread.currentThread().getName());
            if (i == 12) {
                cron = "0/5 * * * * ?";
            }
            if (i == 24) {
                cron = "0/2 * * * * ?";
            }
        }, triggerContext -> {
            CronTrigger cronTrigger = new CronTrigger(cron);
            return cronTrigger.nextExecutionTime(triggerContext);
        });
    }
}

上述例子只是简单的范例,可以根据需要进行改进

总结

spring task配置简单,能够满足实际开发中的大部分需要。但是当需要保护事故现场,或者需要动态的暂停、删除任务的话,spring task就不是很适用了。即使在spring task的基础上去实现这些功能,最终得到的效果可能也并不是很理想。这种时候就需要用到调度框架Quartz了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,099评论 18 139
  • 一碗酸辣粉下肚,呛的眼泪和鼻涕掉进碗里。 如果,你没忘记,我没记错的话。 我想,我听过最动听的一句话,...
    蝈蝈大叔阅读 667评论 0 0
  • Struts2注解 1Struts2注解的作用 使用注解可以用来替换struts.xml配置文件!!! 2导包 必...
    拂清风阅读 780评论 0 1
  • 人性到底是怎么样的?每天各类人群当中有板着脸的、嬉皮笑脸的、温雅可亲的、暴躁焦虑的等等。 我们每天的不开心...
    伟鸿阅读 925评论 0 0
  • 原文: 风萧萧兮易水寒,壮士一去兮不复还。 译文: 时值高秋 萧萧的寒风刮过易水 那悲凉的风 那刺骨的水 壮士呀!...
    燕飞花阅读 1,633评论 5 13