关于 Spring task和线程池

最近因工作需求,研究了一下spring task定时任务,和线程池,有了一定收获,记录一下

涉及如下内容

1、如何实现spring task定时任务的配置

2、task里面的一个job方法如何使用多线程,配置线程池

    如何配置等待子线程结束后,再结束主线程


1、如何实现spring task定时任务的配置

因工作需要,需要定时执行一个方法,通过相关比较后,发现spring自带的task 可以满足,配置简单

步骤

1)增加配置文件 ,在applicationContext-cfg.xml 主配置文件里面添加 相关task标签

  1. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"  
  2.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  3.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  4.        http://www.springframework.org/schema/tx   
  5.        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
  6.        http://www.springframework.org/schema/aop   
  7.        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
  8.        http://www.springframework.org/schema/context   
  9.        http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  10.        http://www.springframework.org/schema/task  
  11.        http://www.springframework.org/schema/task/spring-task-3.0.xsd  
  12.        http://www.springframework.org/schema/jee       
  13.        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">  

2)编写bean类和执行方法  

编写jobService类,里面实现testjobThread方法,调用的spring注入过的action、service方法

  1. @Component("jobService")  
  2. public class jobService  
  3. {  
  4.     private static Logger logger = Logger.getLogger(jobService.class);  
  5.   
  6.     @Autowired  
  7.     private ThreadPoolTaskExecutor taskExecutor;  
  8.     final CountDownLatch countDownLatch = new CountDownLatch(3);   
  9.   
  10.     /**  
  11.     * @Title: DZFP_job  
  12.     * @Description:开票定时任务 
  13.     */  
  14.     public void testjobThread()  
  15.     {  
  16.         Date startdate = new Date();  
  17.         logger.info("DZFP_job_JOB 开始执行任务...,时间   " + startdate);  
  18.         try  
  19.         {  
  20.             DzfpAction.Dzfp_SendAll();  
  21.         }  
  22.         catch (Exception e)  
  23.         {  
  24.             // TODO Auto-generated catch block  
  25.             e.printStackTrace();  
  26.             logger.error(StringUtil.grabExceptionMessage(e));  
  27.         }  
  28.         Date enddate = new Date();  
  29.         logger.info("DZFP_job_JOB 任务完成...时间  " + enddate + "   耗时   " + String.valueOf(enddate.getTime() - startdate.getTime()) + "毫秒");  
  30.     }  


3)配置task相关配置文件,在文件applicationContext-cfg.xml 中增加下列内容

pool-size="5"  该参数主要解决,多个调度并行的问题,如下图5个task任务,建议设置3--5个调度

如果配置参数为 1,下面5个task任务会依次执行,如果一个时间超出,后面的任务一直在等待,影响业务

  1. <!-- 定时任务 -->  
  2. <task:scheduler id="scheduler" pool-size="5" />  
  3. <task:scheduled-tasks scheduler="scheduler">  
  4.     <!-- 每天7点到7点55, 每隔5分钟执行一次 "0 0/5 7 * * ?"-->  
  5.     <task:scheduled ref="jobService" method="DZFPgetInvoie_job" cron="0 0/30 * * * ?" />  
  6.     <task:scheduled ref="jobService" method="DZFPgetInvoie_hong_job" cron="0 0/30 * * * ?" />  
  7.        <span style="white-space:pre;">  </span><task:scheduled ref="jobService" method="testjobThread" cron="0/5 * * * * ?" />  
  8.     <task:scheduled ref="jobService" method="hzgd_job" cron="0/30 * * * * ?" />  
  9.     <task:scheduled ref="jobService" method="alipay_pay_job" cron="0/30 * * * * ?" />  
  10. </task:scheduled-tasks>  

使用以上配置后,启动项目就可以定时执行testjobThread方法里面的业务了。


2、task里面的一个job方法如何使用多线程,配置线程池

经过测试,spring task里面的方法是被串行执行的,比如上面配置的方法 testjobThread方法,5秒执行一次,如果有一个执行过程时间过长,后面的一次调度一直等上次执行结束后,才会启动下一次调用。

也就是说spring task是会监控 执行方法的主线程,如果主线程未结束的话,下一次就不会执行。

根据业务需求,这个testjobThread里面的 业务,需要多线程执行 (批量抽取数据)

spring框架里面,推荐使用线程池

1)配置线程池     在applicationContext-cfg.xml文件中增加配置如下

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



2)修改业务操作类为thread类,实现run()方法

添加计数器CountDownLatch ,控制子线程结束后,再结束主线程

注意对象实现@Scope("prototype"),用到了成员变量参数


  1. package cn.hao24.action;  
  2. import java.util.Date;  
  3. import java.util.concurrent.CountDownLatch;  
  4.   
  5. import org.springframework.context.annotation.Scope;  
  6. import org.springframework.stereotype.Component;  
  7.   
  8. import cn.hao24.util.DateUtil;  
  9. import cn.hao24.util.SpringContextUtils;  
  10.   
  11. @Component("testThreadAction")  
  12. @Scope("prototype")  
  13. public class testThreadAction extends Thread  
  14. {  
  15.   
  16. /** 
  17.  * spring tash默认是单线程 串行执行,即一个方法执行完成前,后面的job不会执行的 
  18.  * 但是如果主方法里面产生了thread线程, 主线程如果不等子线程结束后 就结束的话, task任务会产生多次调度 
  19.  */  
  20.   
  21.     private String Treadname;  
  22.     private CountDownLatch latch;  
  23.       
  24.     public testThreadAction(String Treadname,CountDownLatch latch){  
  25.         this.Treadname=Treadname;  
  26.         this.latch=latch;  
  27.     }  
  28.       
  29.     @Override  
  30.     public void run()  
  31.     {  
  32.   
  33.              
  34.         try  
  35.         {  
  36.             //主业务方法  
  37.             for (int i = 0; i < 10; i++)  
  38.             {  
  39.                 Thread current = Thread.currentThread();  
  40.                 System.out.println("线程号:"+current.getId() +"--"+current.getName()+" --"+Treadname +":---runing--- "+i+"--"+DateUtil.format(new Date(), "yyyyMMddHHmmss") );  
  41.                 Thread.sleep(20000);  
  42.             }  
  43.         }  
  44.         catch (InterruptedException e)  
  45.         {  
  46.             // TODO Auto-generated catch block  
  47.             e.printStackTrace();  
  48.         }finally{  
  49.             //设置实例 执行完毕  
  50.             latch.countDown();  
  51.         }  
  52.                 
  53.     }  
  54.     public void setTreadname(String treadname)  
  55.     {  
  56.         Treadname = treadname;  
  57.     }  
  58.   
  59.   
  60.     public void setLatch(CountDownLatch latch)  
  61.     {  
  62.         this.latch = latch;  
  63.     }  
  64.       
  65.   
  66. }  
2)修改job调度的方法为多线程,配置3个线程
  1. package cn.hao24.job;  
  2.   
  3. import java.util.Date;  
  4. import java.util.concurrent.CountDownLatch;  
  5.   
  6. import javax.annotation.Resource;  
  7.   
  8. import org.apache.log4j.Logger;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  11. import org.springframework.stereotype.Component;  
  12.   
  13. import cn.hao24.action.DzfpAction;  
  14. import cn.hao24.action.HzgdAction;  
  15. import cn.hao24.action.KJGOrderjob;  
  16. import cn.hao24.action.testThreadAction;  
  17. import cn.hao24.service.ZFBService;  
  18. import cn.hao24.util.SpringContextUtils;  
  19. import cn.hao24.util.StringUtil;  
  20.   
  21. @Component("jobService")  
  22. public class jobService  
  23. {  
  24.     private static Logger logger = Logger.getLogger(jobService.class);  
  25.   
  26.     @Autowired  
  27.     private ThreadPoolTaskExecutor taskExecutor;  
  28.     final CountDownLatch countDownLatch = new CountDownLatch(3);   
  29.     public void testjobThread()  
  30.     {  
  31.         try  
  32.         {  
  33.             CountDownLatch latch=new CountDownLatch(3);  //java工具类,类似与计数器,主要实现子线程未结束钱,主线程一直等待  
  34.             testThreadAction test1 = (testThreadAction)SpringContextUtils.getBean("testThreadAction","test1",latch);  
  35.             testThreadAction test2 = (testThreadAction)SpringContextUtils.getBean("testThreadAction","test2",latch);  
  36.             testThreadAction test3 = (testThreadAction)SpringContextUtils.getBean("testThreadAction","test3",latch);  
  37.             taskExecutor.execute(test1);  
  38.             taskExecutor.execute(test2);  
  39.             taskExecutor.execute(test3);  
  40.             latch.await(); //子线程未结束前,一直等待  
  41.             //test1.run();  
  42.         }  
  43.         catch (Exception e)  
  44.         {  
  45.             e.printStackTrace();  
  46.             logger.error(StringUtil.grabExceptionMessage(e));  
  47.         }  
  48.     }  
  49. }  

执行效果如下:

虽然  testjobThread  5秒执行一次,但是因为使用到了 latch.await()   latch.countDown();需要等子线程执行完毕,才会进行下一次job

子线程每次循环,会sleep 20秒,从下面结果看,3个线程 每隔20秒才打印一次。符合最终要求

线程号:29--taskExecutor-3 --test3:---runing--- 0--20170622145500
线程号:28--taskExecutor-2 --test2:---runing--- 0--20170622145500
线程号:27--taskExecutor-1 --test1:---runing--- 0--20170622145500
线程号:28--taskExecutor-2 --test2:---runing--- 1--20170622145520
线程号:27--taskExecutor-1 --test1:---runing--- 1--20170622145520
线程号:29--taskExecutor-3 --test3:---runing--- 1--20170622145520
线程号:29--taskExecutor-3 --test3:---runing--- 2--20170622145540
线程号:28--taskExecutor-2 --test2:---runing--- 2--20170622145540
线程号:27--taskExecutor-1 --test1:---runing--- 2--20170622145540





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值