欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring5源码解析之Spring中的异步和计划任务

程序员文章站 2024-04-01 22:06:04
java提供了许多创建线程池的方式,并得到一个future实例来作为任务结果。对于spring同样小菜一碟,通过其scheduling包就可以做到将任务线程中后台执行。...

java提供了许多创建线程池的方式,并得到一个future实例来作为任务结果。对于spring同样小菜一碟,通过其scheduling包就可以做到将任务线程中后台执行。

在本文的第一部分中,我们将讨论下spring中执行计划任务的一些基础知识。之后,我们将解释这些类是如何一起协作来启动并执行计划任务的。下一部分将介绍计划和异步任务的配置。最后,我们来写个demo,看看如何通过单元测试来编排计划任务。

什么是spring中的异步任务?

在我们正式的进入话题之前,对于spring,我们需要理解下它实现的两个不同的概念:异步任务和调度任务。显然,两者有一个很大的共同点:都在后台工作。但是,它们之间存在了很大差异。调度任务与异步不同,其作用与linux中的cron job完全相同(windows里面也有计划任务)。举个栗子,有一个任务必须每40分钟执行一次,那么,可以通过xml文件或者注解来进行此配置。简单的异步任务在后台执行就好,无需配置执行频率。

因为它们是两种不同的任务类型,它们两个的执行者自然也就不同。第一个看起来有点像java的并发执行器(concurrency executor),这里会有专门去写一篇关于java中的执行器来具体了解。根据spring文档taskexecutor所述,它提供了基于spring的抽象来处理线程池,这点,也可以通过其类的注释去了解。另一个抽象接口是taskscheduler,它用于在将来给定的时间点来安排任务,并执行一次或定期执行。

在分析源码的过程中,发现另一个比较有趣的点是触发器。它存在两种类型:crontrigger或periodtrigger。第一个模拟cron任务的行为。所以我们可以在将来确切时间点提交一个任务的执行。另一个触发器可用于定期执行任务。

spring的异步任务类

让我们从org.springframework.core.task.taskexecutor类的分析开始。你会发现,其简单的不行,它是一个扩展java的executor接口的接口。它的唯一方法也就是是执行,在参数中使用runnable类型的任务。

package org.springframework.core.task;
import java.util.concurrent.executor;
/**
 * simple task executor interface that abstracts the execution
 * of a {@link runnable}.
 *
 * <p>implementations can use all sorts of different execution strategies,
 * such as: synchronous, asynchronous, using a thread pool, and more.
 *
 * <p>equivalent to jdk 1.5's {@link java.util.concurrent.executor}
 * interface; extending it now in spring 3.0, so that clients may declare
 * a dependency on an executor and receive any taskexecutor implementation.
 * this interface remains separate from the standard executor interface
 * mainly for backwards compatibility with jdk 1.4 in spring 2.x.
 *
 * @author juergen hoeller
 * @since 2.0
 * @see java.util.concurrent.executor
 */
@functionalinterface
public interface taskexecutor extends executor {
 /**
 * execute the given {@code task}.
 * <p>the call might return immediately if the implementation uses
 * an asynchronous execution strategy, or might block in the case
 * of synchronous execution.
 * @param task the {@code runnable} to execute (never {@code null})
 * @throws taskrejectedexception if the given task was not accepted
 */
 @override
 void execute(runnable task);
}

相对来说,org.springframework.scheduling.taskscheduler接口就有点复杂了。它定义了一组以schedule开头的名称的方法允许我们定义将来要执行的任务。所有 schedule* 方法返回java.util.concurrent.scheduledfuture实例。spring5中对scheduleatfixedrate方法做了进一步的充实,其实最终调用的还是scheduledfuture<?> scheduleatfixedrate(runnable task, long period);

public interface taskscheduler {
 /**
 * schedule the given {@link runnable}, invoking it whenever the trigger
 * indicates a next execution time.
 * <p>execution will end once the scheduler shuts down or the returned
 * {@link scheduledfuture} gets cancelled.
 * @param task the runnable to execute whenever the trigger fires
 * @param trigger an implementation of the {@link trigger} interface,
 * e.g. a {@link org.springframework.scheduling.support.crontrigger} object
 * wrapping a cron expression
 * @return a {@link scheduledfuture} representing pending completion of the task,
 * or {@code null} if the given trigger object never fires (i.e. returns
 * {@code null} from {@link trigger#nextexecutiontime})
 * @throws org.springframework.core.task.taskrejectedexception if the given task was not accepted
 * for internal reasons (e.g. a pool overload handling policy or a pool shutdown in progress)
 * @see org.springframework.scheduling.support.crontrigger
 */
 @nullable
 scheduledfuture<?> schedule(runnable task, trigger trigger);
 
 /**
 * schedule the given {@link runnable}, invoking it at the specified execution time.
 * <p>execution will end once the scheduler shuts down or the returned
 * {@link scheduledfuture} gets cancelled.
 * @param task the runnable to execute whenever the trigger fires
 * @param starttime the desired execution time for the task
 * (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
 * @return a {@link scheduledfuture} representing pending completion of the task
 * @throws org.springframework.core.task.taskrejectedexception if the given task was not accepted
 * for internal reasons (e.g. a pool overload handling policy or a pool shutdown in progress)
 * 使用了默认实现,值得我们学习使用的,java9中同样可以有私有实现的,从这里我们可以做到我只通过  * 一个接口你来实现,我把其他相应的功能默认实现下,最后调用你自定义实现的接口即可,使接口功能更  * 加一目了然
 * @since 5.0
 * @see #schedule(runnable, date)
 */
 default scheduledfuture<?> schedule(runnable task, instant starttime) {
 return schedule(task, date.from(starttime));
 }
 /**
 * schedule the given {@link runnable}, invoking it at the specified execution time.
 * <p>execution will end once the scheduler shuts down or the returned
 * {@link scheduledfuture} gets cancelled.
 * @param task the runnable to execute whenever the trigger fires
 * @param starttime the desired execution time for the task
 * (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
 * @return a {@link scheduledfuture} representing pending completion of the task
 * @throws org.springframework.core.task.taskrejectedexception if the given task was not accepted
 * for internal reasons (e.g. a pool overload handling policy or a pool shutdown in progress)
 */
 scheduledfuture<?> schedule(runnable task, date starttime);
...
/**
 * schedule the given {@link runnable}, invoking it at the specified execution time
 * and subsequently with the given period.
 * <p>execution will end once the scheduler shuts down or the returned
 * {@link scheduledfuture} gets cancelled.
 * @param task the runnable to execute whenever the trigger fires
 * @param starttime the desired first execution time for the task
 * (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
 * @param period the interval between successive executions of the task
 * @return a {@link scheduledfuture} representing pending completion of the task
 * @throws org.springframework.core.task.taskrejectedexception if the given task was not accepted
 * for internal reasons (e.g. a pool overload handling policy or a pool shutdown in progress)
 * @since 5.0
 * @see #scheduleatfixedrate(runnable, date, long)
 */
 default scheduledfuture<?> scheduleatfixedrate(runnable task, instant starttime, duration period) {
 return scheduleatfixedrate(task, date.from(starttime), period.tomillis());
 }
 /**
 * schedule the given {@link runnable}, invoking it at the specified execution time
 * and subsequently with the given period.
 * <p>execution will end once the scheduler shuts down or the returned
 * {@link scheduledfuture} gets cancelled.
 * @param task the runnable to execute whenever the trigger fires
 * @param starttime the desired first execution time for the task
 * (if this is in the past, the task will be executed immediately, i.e. as soon as possible)
 * @param period the interval between successive executions of the task (in milliseconds)
 * @return a {@link scheduledfuture} representing pending completion of the task
 * @throws org.springframework.core.task.taskrejectedexception if the given task was not accepted
 * for internal reasons (e.g. a pool overload handling policy or a pool shutdown in progress)
 */
 scheduledfuture<?> scheduleatfixedrate(runnable task, date starttime, long period);
...
}

之前提到两个触发器组件,都实现了org.springframework.scheduling.trigger接口。这里,我们只需关注一个的方法nextexecutiontime ,其定义下一个触发任务的执行时间。它的两个实现,crontrigger和periodictrigger,由org.springframework.scheduling.triggercontext来实现信息的存储,由此,我们可以很轻松获得一个任务的最后一个执行时间(lastscheduledexecutiontime),给定任务的最后完成时间(lastcompletiontime)或最后一个实际执行时间(lastactualexecutiontime)。接下来,我们通过阅读源代码来简单的了解下这些东西。org.springframework.scheduling.concurrent.concurrenttaskscheduler包含一个私有类enterpriseconcurrenttriggerscheduler。在这个class里面,我们可以找到schedule方法:

public scheduledfuture<?> schedule(runnable task, final trigger trigger) {
 managedscheduledexecutorservice executor = (managedscheduledexecutorservice) scheduledexecutor;
 return executor.schedule(task, new javax.enterprise.concurrent.trigger() {
  @override
  public date getnextruntime(lastexecution le, date taskscheduledtime) {
   return trigger.nextexecutiontime(le != null ?
    new simpletriggercontext(le.getscheduledstart(), le.getrunstart(), le.getrunend()) :
    new simpletriggercontext());
  }
  @override
  public boolean skiprun(lastexecution lastexecution, date scheduledruntime) {
   return false;
  }
 });
}

simpletriggercontext从其名字就可以看到很多东西了,因为它实现了triggercontext接口。

/**
 * simple data holder implementation of the {@link triggercontext} interface.
 *
 * @author juergen hoeller
 * @since 3.0
 */
public class simpletriggercontext implements triggercontext {
 @nullable
 private volatile date lastscheduledexecutiontime;
 @nullable
 private volatile date lastactualexecutiontime;
 @nullable
 private volatile date lastcompletiontime;
...
 /**
 * create a simpletriggercontext with the given time values.
 * @param lastscheduledexecutiontime last <i>scheduled</i> execution time
 * @param lastactualexecutiontime last <i>actual</i> execution time
 * @param lastcompletiontime last completion time
 */
 public simpletriggercontext(date lastscheduledexecutiontime, date lastactualexecutiontime, date lastcompletiontime) {
 this.lastscheduledexecutiontime = lastscheduledexecutiontime;
 this.lastactualexecutiontime = lastactualexecutiontime;
 this.lastcompletiontime = lastcompletiontime;
 }
 ...
}

也正如你看到的,在构造函数中设置的时间值来自javax.enterprise.concurrent.lastexecution的实现,其中:

  • getscheduledstart:返回上次开始执行任务的时间。它对应于triggercontext的lastscheduledexecutiontime属性。
  • getrunstart:返回给定任务开始运行的时间。在triggercontext中,它对应于lastactualexecutiontime。
  • getrunend:任务终止时返回。它用于在triggercontext中设置lastcompletiontime。

spring调度和异步执行中的另一个重要类是org.springframework.core.task.support.taskexecutoradapter。它是一个将java.util.concurrent.executor作为spring基本的执行器的适配器(描述的有点拗口,看下面代码就明了了),之前已经描述了taskexecutor。实际上,它引用了java的executorservice,它也是继承了executor接口。此引用用于完成所有提交的任务。

/**
 * adapter that takes a jdk {@code java.util.concurrent.executor} and
 * exposes a spring {@link org.springframework.core.task.taskexecutor} for it.
 * also detects an extended {@code java.util.concurrent.executorservice 从此解释上面的说明}, adapting
 * the {@link org.springframework.core.task.asynctaskexecutor} interface accordingly.
 *
 * @author juergen hoeller
 * @since 3.0
 * @see java.util.concurrent.executor
 * @see java.util.concurrent.executorservice 
 * @see java.util.concurrent.executors
 */
public class taskexecutoradapter implements asynclistenabletaskexecutor {
 private final executor concurrentexecutor;
 @nullable
 private taskdecorator taskdecorator;
 ...
  /**
 * create a new taskexecutoradapter,
 * using the given jdk concurrent executor.
 * @param concurrentexecutor the jdk concurrent executor to delegate to
 */
 public taskexecutoradapter(executor concurrentexecutor) {
 assert.notnull(concurrentexecutor, "executor must not be null");
 this.concurrentexecutor = concurrentexecutor;
 }
  /**
 * delegates to the specified jdk concurrent executor.
 * @see java.util.concurrent.executor#execute(runnable)
 */
 @override
 public void execute(runnable task) {
 try {
  doexecute(this.concurrentexecutor, this.taskdecorator, task);
 }
 catch (rejectedexecutionexception ex) {
  throw new taskrejectedexception(
   "executor [" + this.concurrentexecutor + "] did not accept task: " + task, ex);
 }
 }
 @override
 public void execute(runnable task, long starttimeout) {
 execute(task);
 }
 @override
 public future<?> submit(runnable task) {
 try {
  if (this.taskdecorator == null && this.concurrentexecutor instanceof executorservice) {
  return ((executorservice) this.concurrentexecutor).submit(task);
  }
  else {
  futuretask<object> future = new futuretask<>(task, null);
  doexecute(this.concurrentexecutor, this.taskdecorator, future);
  return future;
  }
 }
 catch (rejectedexecutionexception ex) {
  throw new taskrejectedexception(
   "executor [" + this.concurrentexecutor + "] did not accept task: " + task, ex);
 }
 }
 ...
}

在spring中配置异步和计划任务

下面我们通过代码的方式来实现异步任务。首先,我们需要通过注解来启用配置。它的xml配置如下:

<task:scheduler id="taskscheduler"/>
<task:executor id="taskexecutor" pool-size="2" />
<task:annotation-driven executor="taskexecutor" scheduler="taskscheduler"/>
<context:component-scan base-package="com.migo.async"/>

可以通过将@enablescheduling和@enableasync注解添加到配置类(用@configuration注解)来激活两者。完事,我们就可以开始着手实现调度和异步任务。为了实现调度任务,我们可以使用@scheduled注解。我们可以从org.springframework.scheduling.annotation包中找到这个注解。它包含了以下几个属性:

  • cron:使用cron风格(linux配置定时任务的风格)的配置来配置需要启动的带注解的任务。
  • zone:要解析cron表达式的时区。
  • fixeddelay或fixeddelaystring:在固定延迟时间后执行任务。即任务将在最后一次调用结束和下一次调用的开始之间的这个固定时间段后执行。
  • fixedrate或fixedratestring:使用fixedrate注解的方法的调用将以固定的时间段(例如:每10秒钟)进行,与执行生命周期(开始,结束)无关。
  • initialdelay或initialdelaystring:延迟首次执行调度方法的时间。请注意,所有值(fixeddelay ,fixedrate ,initialdelay )必须以毫秒表示。 需要特别记住的是 ,用@scheduled注解的方法不能接受任何参数,并且不返回任何内容(void),如果有返回值,返回值也会被忽略掉的,没什么卵用。定时任务方法由容器管理,而不是由调用者在运行时调用。它们由 org.springframework.scheduling.annotation.scheduledannotationbeanpostprocessor来解析,其中包含以下方法来拒绝执行所有不正确定义的函数:
protected void processscheduled(scheduled scheduled, method method, object bean) {
 try {
  assert.istrue(method.getparametercount() == 0,
   "only no-arg methods may be annotated with @scheduled");
 /**
 *  之前的版本中直接把返回值非空的给拒掉了,在spring 4.3 spring5 的版本中就没那么严格了
   * assert.istrue(void.class.equals(method.getreturntype()),
   *        "only void-returning methods may be annotated with @scheduled");
   **/        
// ...
/**
 * 注释很重要
 * an annotation that marks a method to be scheduled. exactly one of
 * the {@link #cron()}, {@link #fixeddelay()}, or {@link #fixedrate()}
 * attributes must be specified.
 *
 * <p>the annotated method must expect no arguments. it will typically have
 * a {@code void} return type; if not, the returned value will be ignored
 * when called through the scheduler.
 *
 * <p>processing of {@code @scheduled} annotations is performed by
 * registering a {@link scheduledannotationbeanpostprocessor}. this can be
 * done manually or, more conveniently, through the {@code <task:annotation-driven/>}
 * element or @{@link enablescheduling} annotation.
 *
 * <p>this annotation may be used as a <em>meta-annotation</em> to create custom
 * <em>composed annotations</em> with attribute overrides.
 *
 * @author mark fisher
 * @author dave syer
 * @author chris beams
 * @since 3.0
 * @see enablescheduling
 * @see scheduledannotationbeanpostprocessor
 * @see schedules
 */
@target({elementtype.method, elementtype.annotation_type})
@retention(retentionpolicy.runtime)
@documented
@repeatable(schedules.class)
public @interface scheduled {
...
}

使用@async注解标记一个方法或一个类(通过标记一个类,我们自动将其所有方法标记为异步)。与@scheduled不同,异步任务可以接受参数,并可能返回某些东西。

写一个在spring中执行异步任务的demo

有了上面这些知识,我们可以来编写异步和计划任务。我们将通过测试用例来展示。我们从不同的任务执行器(task executors)的测试开始:

@runwith(springjunit4classrunner.class)
@contextconfiguration(locations={"classpath:applicationcontext-test.xml"})
@webappconfiguration
public class taskexecutorstest {
 
 @test
 public void simpeasync() throws interruptedexception {
  /**
   * simpleasynctaskexecutor creates new thread for every task and executes it asynchronously. the threads aren't reused as in 
   * native java's thread pools.
   * 
   * the number of concurrently executed threads can be specified through concurrencylimit bean property 
   * (concurrencylimit xml attribute). here it's more simple to invoke setconcurrencylimit method. 
   * here the tasks will be executed by 2 simultaneous threads. without specifying this value,
   * the number of executed threads will be indefinite.
   * 
   * you can observe that only 2 tasks are executed at a given time - even if 3 are submitted to execution (lines 40-42).
   **/
  simpleasynctaskexecutor executor = new simpleasynctaskexecutor("thread_name_prefix_____");
  executor.setconcurrencylimit(2);
  executor.execute(new simpletask("simpleasynctask-1", counters.simpleasynctask, 1000));
  executor.execute(new simpletask("simpleasynctask-2", counters.simpleasynctask, 1000));
 
  thread.sleep(1050);
  asserttrue("2 threads should be terminated, but "+counters.simpleasynctask.getnb()+" were instead", counters.simpleasynctask.getnb() == 2);
 
  executor.execute(new simpletask("simpleasynctask-3", counters.simpleasynctask, 1000));
  executor.execute(new simpletask("simpleasynctask-4", counters.simpleasynctask, 1000));
  executor.execute(new simpletask("simpleasynctask-5", counters.simpleasynctask, 2000));
   
  thread.sleep(1050);
  asserttrue("4 threads should be terminated, but "+counters.simpleasynctask.getnb()+" were instead", counters.simpleasynctask.getnb() == 4);
  executor.execute(new simpletask("simpleasynctask-6", counters.simpleasynctask, 1000));
 
  thread.sleep(1050);
  asserttrue("6 threads should be terminated, but "+counters.simpleasynctask.getnb()+" were instead", 
   counters.simpleasynctask.getnb() == 6);
 }
  
 @test
 public void synctasktest() {
  /**
   * synctask works almost as java's countdownlatch. in fact, this executor is synchronous with the calling thread. in our case,
   * synctaskexecutor tasks will be synchronous with junit thread. it means that the testing thread will sleep 5 
   * seconds after executing the third task ('synctask-3'). to prove that, we check if the total execution time is ~5 seconds.
   **/
  long start = system.currenttimemillis();
  synctaskexecutor executor = new synctaskexecutor();
  executor.execute(new simpletask("synctask-1", counters.synctask, 0));
  executor.execute(new simpletask("synctask-2", counters.synctask, 0));
  executor.execute(new simpletask("synctask-3", counters.synctask, 0));
  executor.execute(new simpletask("synctask-4", counters.synctask, 5000));
  executor.execute(new simpletask("synctask-5", counters.synctask, 0));
  long end = system.currenttimemillis();
  int exectime = math.round((end-start)/1000);
  asserttrue("execution time should be 5 seconds but was "+exectime+" seconds", exectime == 5); 
 }
  
 @test
 public void threadpooltest() throws interruptedexception {
  /**
   * this executor can be used to expose java's native threadpoolexecutor as spring bean, with the 
   * possibility to set core pool size, max pool size and queue capacity through bean properties.
   * 
   * it works exactly as threadpoolexecutor from java.util.concurrent package. it means that our pool starts 
   * with 2 threads (core pool size) and can be growth until 3 (max pool size).
   * in additionally, 1 task can be stored in the queue. this task will be treated 
   * as soon as one from 3 threads ends to execute provided task. in our case, we try to execute 5 tasks
   * in 3 places pool and 1 place queue. so the 5th task should be rejected and taskrejectedexception should be thrown.
   **/
  threadpooltaskexecutor executor = new threadpooltaskexecutor();
  executor.setcorepoolsize(2);
  executor.setmaxpoolsize(3);
  executor.setqueuecapacity(1);
  executor.initialize();
 
  executor.execute(new simpletask("threadpooltask-1", counters.threadpool, 1000));
  executor.execute(new simpletask("threadpooltask-2", counters.threadpool, 1000));
  executor.execute(new simpletask("threadpooltask-3", counters.threadpool, 1000));
  executor.execute(new simpletask("threadpooltask-4", counters.threadpool, 1000));
  boolean wastre = false;
  try {
   executor.execute(new simpletask("threadpooltask-5", counters.threadpool, 1000));
  } catch (taskrejectedexception tre) {
   wastre = true;
  }
  asserttrue("the last task should throw a taskrejectedexception but it wasn't", wastre);
 
  thread.sleep(3000);
 
  asserttrue("4 tasks should be terminated, but "+counters.threadpool.getnb()+" were instead", 
   counters.threadpool.getnb()==4);
 }
 
}
 
class simpletask implements runnable {
 private string name;
 private counters counter;
 private int sleeptime;
  
 public simpletask(string name, counters counter, int sleeptime) {
  this.name = name;
  this.counter = counter;
  this.sleeptime = sleeptime;
 }
  
 @override
 public void run() {
  try {
   thread.sleep(this.sleeptime);
  } catch (interruptedexception e) {
   e.printstacktrace();
  }
  this.counter.increment();
  system.out.println("running task '"+this.name+"' in thread "+thread.currentthread().getname());
 }
  
 @override
 public string tostring() {
     return "task {"+this.name+"}";
 }
}
 
enum counters {
     
 simpleasynctask(0),
 synctask(0),
 threadpool(0);
  
 private int nb;
  
 public int getnb() {
  return this.nb;
 }
  
 public synchronized void increment() {
  this.nb++;
 }
 
 private counters(int n) {
  this.nb = n;
 }
}

在过去,我们可以有更多的执行器可以使用(simplethreadpooltaskexecutor,timertaskexecutor 这些都2.x 3.x的老古董了)。但都被弃用并由本地java的执行器取代成为spring的首选。看看输出的结果:

running task 'simpleasynctask-1' in thread thread_name_prefix_____1
running task 'simpleasynctask-2' in thread thread_name_prefix_____2
running task 'simpleasynctask-3' in thread thread_name_prefix_____3
running task 'simpleasynctask-4' in thread thread_name_prefix_____4
running task 'simpleasynctask-5' in thread thread_name_prefix_____5
running task 'simpleasynctask-6' in thread thread_name_prefix_____6
running task 'synctask-1' in thread main
running task 'synctask-2' in thread main
running task 'synctask-3' in thread main
running task 'synctask-4' in thread main
running task 'synctask-5' in thread main
running task 'threadpooltask-2' in thread threadpooltaskexecutor-2
running task 'threadpooltask-1' in thread threadpooltaskexecutor-1
running task 'threadpooltask-4' in thread threadpooltaskexecutor-3
running task 'threadpooltask-3' in thread threadpooltaskexecutor-2

以此我们可以推断出,第一个测试为每个任务创建新的线程。通过使用不同的线程名称,我们可以看到相应区别。第二个,同步执行器,应该执行所调用线程中的任务。这里可以看到'main'是主线程的名称,它的主线程调用执行同步所有任务。最后一种例子涉及最大可创建3个线程的线程池。从结果可以看到,他们也确实只有3个创建线程。

现在,我们将编写一些单元测试来看看@async和@scheduled实现。

@runwith(springjunit4classrunner.class)
@contextconfiguration(locations={"classpath:applicationcontext-test.xml"})
@webappconfiguration
public class annotationtest {
 
 @autowired
 private genericapplicationcontext context;
     
 @test
 public void testscheduled() throws interruptedexception {
 
   system.out.println("start sleeping");
   thread.sleep(6000);
   system.out.println("wake up !");
 
   testscheduledtask scheduledtask = (testscheduledtask) context.getbean("testscheduledtask");
    /**
    * test fixed delay. it's executed every 6 seconds. the first execution is registered after application's context start. 
    **/
   asserttrue("scheduled task should be executed 2 times (1 before sleep in this method, 1 after the sleep), but was "+scheduledtask.getfixeddelaycounter(), 
    scheduledtask.getfixeddelaycounter() == 2);
    
    /**
    * test fixed rate. it's executed every 6 seconds. the first execution is registered after application's context start. 
    * unlike fixed delay, a fixed rate configuration executes one task with specified time. for example, it will execute on 
    * 6 seconds delayed task at 10:30:30, 10:30:36, 10:30:42 and so on - even if the task 10:30:30 taken 30 seconds to 
    * be terminated. in teh case of fixed delay, if the first task takes 30 seconds, the next will be executed 6 seconds 
    * after the first one, so the execution flow will be: 10:30:30, 10:31:06, 10:31:12.
    **/
   asserttrue("scheduled task should be executed 2 times (1 before sleep in this method, 1 after the sleep), but was "+scheduledtask.getfixedratecounter(), 
    scheduledtask.getfixedratecounter() == 2);
    /**
    * test fixed rate with initial delay attribute. the initialdelay attribute is set to 6 seconds. it causes that 
    * scheduled method is executed 6 seconds after application's context start. in our case, it should be executed 
    * only once because of previous thread.sleep(6000) invocation.
    **/
   asserttrue("scheduled task should be executed 1 time (0 before sleep in this method, 1 after the sleep), but was "+scheduledtask.getinitialdelaycounter(), scheduledtask.getinitialdelaycounter() == 1);
    /**
    * test cron scheduled task. cron is scheduled to be executed every 6 seconds. it's executed only once, 
    * so we can deduce that it's not invoked directly before applications 
    * context start, but only after configured time (6 seconds in our case).
    **/
   asserttrue("scheduled task should be executed 1 time (0 before sleep in this method, 1 after the sleep), but was "+scheduledtask.getcroncounter(), scheduledtask.getcroncounter() == 1);
 }
     
 @test
 public void testasyc() throws interruptedexception {
    /**
    * to test @async annotation, we can create a bean in-the-fly. asynccounter bean is a
    * simple counter which value should be equals to 2 at the end of the test. a supplementary test
    * concerns threads which execute both of asynccounter methods: one which 
    * isn't annotated with @async and another one which is annotated with it. for the first one, invoking
    * thread should have the same name as the main thread. for annotated method, it can't be executed in 
    * the main thread. it must be executed asynchrounously in a new thread.
    **/
   context.registerbeandefinition("asynccounter", new rootbeandefinition(asynccounter.class));
    
   string currentname = thread.currentthread().getname();
   asynccounter asynccounter = context.getbean("asynccounter", asynccounter.class);
   asynccounter.incrementnormal();
   asserttrue("thread executing normal increment should be the same as junit thread but it wasn't (expected '"+currentname+"', got '"+asynccounter.getnormalthreadname()+"')",
           asynccounter.getnormalthreadname().equals(currentname));
   asynccounter.incrementasync();
   // sleep 50ms and give some time to asynccounter to update asyncthreadname value
   thread.sleep(50);
 
   assertfalse("thread executing @async increment shouldn't be the same as junit thread but it wasn (junit thread '"+currentname+"', @async thread '"+asynccounter.getasyncthreadname()+"')",
           asynccounter.getasyncthreadname().equals(currentname));
   system.out.println("main thread execution's name: "+currentname);
   system.out.println("asynccounter normal increment thread execution's name: "+asynccounter.getnormalthreadname());
   system.out.println("asynccounter @async increment thread execution's name: "+asynccounter.getasyncthreadname());
   asserttrue("counter should be 2, but was "+asynccounter.getcounter(), asynccounter.getcounter()==2);
 }
 
}
 
class asynccounter {
     
 private int counter = 0;
 private string normalthreadname;
 private string asyncthreadname;
  
 public void incrementnormal() {
  normalthreadname = thread.currentthread().getname();
  this.counter++;
 }
  
 @async
 public void incrementasync() {
  asyncthreadname = thread.currentthread().getname();
  this.counter++;
 }
  
 public string getasyncthreadname() {
  return asyncthreadname;
 }
  
 public string getnormalthreadname() {
  return normalthreadname;
 }
  
 public int getcounter() {
  return this.counter;
 }
     
}

另外,我们需要创建新的配置文件和一个包含定时任务方法的类:

<!-- imported configuration file first -->
<!-- activates various annotations to be detected in bean classes -->
<context:annotation-config />
 
<!-- scans the classpath for annotated components that will be auto-registered as spring beans.
 for example @controller and @service. make sure to set the correct base-package-->
<context:component-scan base-package="com.migo.test.schedulers" />
 
<task:scheduler id="taskscheduler"/>
<task:executor id="taskexecutor" pool-size="40" />
<task:annotation-driven executor="taskexecutor" scheduler="taskscheduler"/>
// scheduled methods after, all are executed every 6 seconds (scheduledatfixedrate and scheduledatfixeddelay start to execute at
// application context start, two other methods begin 6 seconds after application's context start)
@component
public class testscheduledtask {
 
 private int fixedratecounter = 0;
 private int fixeddelaycounter = 0;
 private int initialdelaycounter = 0;
 private int croncounter = 0;
 
 @scheduled(fixedrate = 6000)
 public void scheduledatfixedrate() {
  system.out.println("<r> increment at fixed rate");
  fixedratecounter++;
 }
  
 @scheduled(fixeddelay = 6000)
 public void scheduledatfixeddelay() {
  system.out.println("<d> incrementing at fixed delay");
  fixeddelaycounter++;
 }
  
 @scheduled(fixeddelay = 6000, initialdelay = 6000)
 public void scheduledwithinitialdelay() {
  system.out.println("<di> incrementing with initial delay");
  initialdelaycounter++;
 }
  
 @scheduled(cron = "**/6 ** ** ** ** **")
 public void scheduledwithcron() {
  system.out.println("<c> incrementing with cron");
  croncounter++;
      
 }
  
 public int getfixedratecounter() {
  return this.fixedratecounter;
 }
  
 public int getfixeddelaycounter() {
  return this.fixeddelaycounter;
 }
  
 public int getinitialdelaycounter() {
  return this.initialdelaycounter;
 }
  
 public int getcroncounter() {
  return this.croncounter;
 }
     
}

该测试的输出:

<r> increment at fixed rate
<d> incrementing at fixed delay
start sleeping
<c> incrementing with cron
<di> incrementing with initial delay
<r> increment at fixed rate
<d> incrementing at fixed delay
wake up !
main thread execution's name: main
asynccounter normal increment thread execution's name: main
asynccounter @async increment thread execution's name: taskexecutor-1

本文向我们介绍了关于spring框架另一个大家比较感兴趣的功能–定时任务。我们可以看到,与linux cron风格配置类似,这些任务同样可以按照固定的频率进行定时任务的设置。我们还通过例子证明了使用@async注解的方法会在不同线程中执行。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。