Spring TaskExecutor与TaskScheduler

Spring Task为Spring3.0后加入的自主开发定时任务工具,区别于集成Timer与Quartz,Spring Task不需要额外的jar包,使用方便分为注解和配置文件两种形式。

Spring TaskExecutor主要用来创建线程池用来管理异步定时任务开启的线程。(防止建立线程过多导致资源浪费)

Spring TaskScheduler创建定时任务

首先按照官网介绍一个使用线程池的例子:

 

import org.springframework.core.task.TaskExecutor;

public class TaskExecutorExample {

  private class MessagePrinterTask implements Runnable {

    private String message;

    public MessagePrinterTask(String message) {
      this.message = message;
    }

    public void run() {
      System.out.println(message);
    }

  }

  private TaskExecutor taskExecutor;

  public TaskExecutorExample(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
  }

  public void printMessages() {
    for(int i = 0; i < 25; i++) {
      taskExecutor.execute(new MessagePrinterTask("Message" + i));
    }
  }
} org.springframework.core.task.TaskExecutor;

public class TaskExecutorExample {

  private class MessagePrinterTask implements Runnable {

    private String message;

    public MessagePrinterTask(String message) {
      this.message = message;
    }

    public void run() {
      System.out.println(message);
    }

  }

  private TaskExecutor taskExecutor;

  public TaskExecutorExample(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
  }

  public void printMessages() {
    for(int i = 0; i < 25; i++) {
      taskExecutor.execute(new MessagePrinterTask("Message" + i));
    }
  }
}

xml配置

 

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  <property name="corePoolSize" value="5" />
  <property name="maxPoolSize" value="10" />
  <property name="queueCapacity" value="25" />
</bean>

<bean id="taskExecutorExample" class="TaskExecutorExample">
  <constructor-arg ref="taskExecutor" />
</bean> id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  <property name="corePoolSize" value="5" />
  <property name="maxPoolSize" value="10" />
  <property name="queueCapacity" value="25" />
</bean>

<bean id="taskExecutorExample" class="TaskExecutorExample">
  <constructor-arg ref="taskExecutor" />
</bean>

如上文将通过将实现Runnable接口的对象放入TaskExecutor队列中,由TaskExecutor处理新建线程(taskExecutor.execute())

下面介绍通过配置XML来配置定时任务如下:

<!-- 定时任务 -->
	<task:scheduler id="scheduler" pool-size="5" />
	<task:scheduled-tasks scheduler="scheduler">
		<!-- 每天7点到7点55, 每隔5分钟执行一次 "0 0/5 7 * * ?"-->
		<task:scheduled ref="jobService" method="job1" cron="0/5 * * * * ?" />
		<task:scheduled ref="jobService" method="job2" cron="0/5 * * * * ?" />
                <task:scheduled ref="jobService" method="job3" cron="0/5 * * * * ?" />
		<task:scheduled ref="jobService" method="job4" cron="0/30 * * * * ?" />
		<task:scheduled ref="jobService" method="job5" cron="0/30 * * * * ?" />
	</task:scheduled-tasks>

其中 ref为方法所在的bean,method为bean中的方法,cron表达式代表执行频率,特别需要注意的是pool-size="5",默认为1即定时任务下串行调度task任务,如果一个时间超出,后面的任务一直等待影响业务,所以需要配置线程池来并行调度。

线程池配置如下:

<!-- spring线程池-->             
	<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
	    <!-- 线程池维护线程的最少数量 -->  
	    <property name="corePoolSize" value="5" />  
	    <!-- 线程池维护线程所允许的空闲时间,默认为60s  -->  
	    <property name="keepAliveSeconds" value="200" />  
	    <!-- 线程池维护线程的最大数量 -->  
	    <property name="maxPoolSize" value="20" />  
	    <!-- 缓存队列最大长度 -->  
	    <property name="queueCapacity" value="20" />  
	    <!-- 对拒绝task的处理策略   线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者-->  
	    <property name="rejectedExecutionHandler">  
	    <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->  
	        <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->  
	        <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->  
	        <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->  
	        <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />  
	    </property>  
    	<property name="waitForTasksToCompleteOnShutdown" value="true" />  
	</bean>  

 

<task:executor id="taskExecutor" keep-alive="200" pool-size="5-20" queue-capacity="20" rejection-policy="ABORT"/>

文中已经有备注个字段作用已经很明确了。

<task:annotation-driven  executor = "taskExecutor"  scheduler = "scheduler" /> 

将定时任务与线程池关联,开启异步方法。

具体java程序如下:

package com.test.demo.server.imp;

import java.util.Date;

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

@Component("jobService") 
public class jobService  { 
	
	@Async
	public void job1(){
		
		try {
			Thread.sleep(10000l);
			Date startdate = new Date();
			System.out.println(startdate+"job1"+Thread.currentThread());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void job2(){
			
			try {
				Thread.sleep(10000l);
				Date startdate = new Date();
				System.out.println(startdate+"job2"+Thread.currentThread());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	public void job3(){
		
		try {
			Thread.sleep(10000l);
			Date startdate = new Date();
			System.out.println(startdate+"job3"+Thread.currentThread());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void job4(){
		
		try {
			Thread.sleep(10000l);
			Date startdate = new Date();
			System.out.println(startdate+"job4"+Thread.currentThread());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void job5(){
		
		try {
			Thread.sleep(10000l);
			Date startdate = new Date();
			System.out.println(startdate+"job5"+Thread.currentThread());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

注意任务job1为异步调用

启动项目打印如下:

可以看到异步调用定时任务通过以上配置线程创建交给了线程池。

所有xml配置如下

<?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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    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.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/aop
						http://www.springframework.org/schema/aop/spring-aop.xsd
						http://www.springframework.org/schema/tx
						http://www.springframework.org/schema/tx/spring-tx.xsd
      					http://www.springframework.org/schema/task 
      					http://www.springframework.org/schema/task/spring-task.xsd 
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描 -->  
    <context:component-scan base-package="com.test.demo" />
    
    <!-- 定时任务 -->
	<task:scheduler id="scheduler" pool-size="5" />
	<task:scheduled-tasks scheduler="scheduler">
		<task:scheduled ref="jobService" method="job1" cron="0/5 * * * * ?" />
		<task:scheduled ref="jobService" method="job2" cron="0/5 * * * * ?" />
                <task:scheduled ref="jobService" method="job3" cron="0/5 * * * * ?" />
		<task:scheduled ref="jobService" method="job4" cron="0/30 * * * * ?" />
		<task:scheduled ref="jobService" method="job5" cron="0/30 * * * * ?" />
	</task:scheduled-tasks>
    <!-- spring线程池-->             
	
	<task:executor id="taskExecutor" keep-alive="200" pool-size="5-20" queue-capacity="20" rejection-policy="ABORT"/>
	<task:annotation-driven  executor = "taskExecutor"  scheduler = "scheduler" />
</beans>

 

注释配置:

 

注释配置无需配置task:scheduled-tasks只需要在需要执行定时任务的方法上添加@Scheduled即可java代码如下图:

@Scheduled(cron="0/5 * * * * ?")
	@Async
	public void job1(){
		
		try {
			Thread.sleep(10000l);
			Date startdate = new Date();
			System.out.println(startdate+"job1"+Thread.currentThread());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

个人感觉还是配置文件好用一点。

以上就是对于Spring TaskExecutor与TaskScheduler的总结,文中的例子都实际操作过,如发现有问题请联系我,大家一起讨论。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值