spring定時任務.線程池,自訂多線程配置_Quartz

來源:互聯網
上載者:User

定時任務及多線程配置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:context="http://www.springframework.org/schema/context"       xmlns:mvc="http://www.springframework.org/schema/mvc"       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-4.0.xsd       http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd       ">     <!--  job start-->        <!-- 定時 -->    <bean id="ruleBean"        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">        <property name="targetObject" ref="ruleService" />        <property name="targetMethod" value="updateRule" />              </bean>     <bean id="rule" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">        <property name="jobDetail" ref="ruleBean" />        <!-- 每天淩晨一點執行 -->        <property name="cronExpression" value="0 0 1 * * ?"/>    </bean>        <!-- 定時 end -->        <bean id="startQuertz" lazy-init="false" autowire="no"        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">         <property name="jobDetails">          <list>            <ref bean="ruleBean" />          </list>        </property>        <property name="triggers">          <list>             <ref bean="rule" />          </list>        </property>        <!-- 啟動時延期10秒開始任務 -->        <property name="startupDelay" value="10" />    </bean>        <!--  job end-->        <bean id="threadPoolTaskExecutor"      class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">      <!-- 核心線程數,預設為1 -->      <property name="corePoolSize" value="1" />      <!-- 最大線程數,預設為Integer.MAX_VALUE -->      <property name="maxPoolSize" value="10" />      <!-- 隊列最大長度,一般需要設定值>=notifyScheduledMainExecutor.maxNum;預設為Integer.MAX_VALUE          <property name="queueCapacity" value="1000" /> -->      <!-- 線程池維護線程所允許的空閑時間,預設為60s -->      <property name="keepAliveSeconds" value="300" />      <!-- 線程池對拒絕任務(無線程可用)的處理策略,目前只支援AbortPolicy、CallerRunsPolicy;預設為後者 -->      <property name="rejectedExecutionHandler">          <!-- AbortPolicy:直接拋出java.util.concurrent.RejectedExecutionException異常 -->          <!-- CallerRunsPolicy:主線程直接執行該任務,執行完之後嘗試添加下一個任務到線程池中,可以有效降低向線程池內新增工作的速度 -->          <!-- DiscardOldestPolicy:拋棄舊的任務、暫不支援;會導致被丟棄的任務無法再次被執行 -->          <!-- DiscardPolicy:拋棄當前任務、暫不支援;會導致被丟棄的任務無法再次被執行 -->          <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />      </property>    </bean>       <bean id="contextUtil" class="com.mythopoet.util.ContextUtil"></bean></beans>

定時任務JAVA類

RuleService.java

@Servicepublic class RuleService {    public void updateRule(){          System.out.println("定時任務啟動");        }}

多線程配置

StartTaskThread.java

public class StartTaskThread implements Runnable {     private List<String> list;        public StartTaskThread(List<String> list) {       this.list= list;    }    @Override    public synchronized void run() {           System.out.println(list.size());    }}

修改定時任務類,分配資料,並發布到各個線程裡。

RuleService.java

@Servicepublic class RuleService {    public void updateRule(){
        int nums = 5;//開啟5線程        List<String> strList= new ArrayList<String>();        for (int i = 0; i < 2000; i++) {            strList.add("test"+i);        }        Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();        for (int i = 0; i < nums; i++) {            List<String> list = new ArrayList<String>();            map.put(i, list);        }        int st = 0; //起點        int avg = strList.size()/nums; //平均值        int count =0;//記錄值                for (int i = 0; i < nums; i++) {            if(i==nums-1){                for (int j = count; j <strList.size(); j++) {                    map.get(i).add(strList.get(j));                    count++;                }                new Thread(new StartTaskThread(map.get(i)).start();                break;            }            for (int j = st; j <(st+avg); j++) {                map.get(i).add(strList.get(j));                count++;            }            st=st+avg;
            new Thread(new StartTaskThread(map.get(i)).start();
 } }

取線程組態工具類,如果線程內需要操作DAO 則需要主動擷取spring注入的DAO類的Bean

ContextUtil.java

import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class ContextUtil implements ApplicationContextAware{    private static ApplicationContext context;    @Override    public void setApplicationContext(ApplicationContext applicationContext)            throws BeansException {        context = applicationContext;    }    public static ApplicationContext getContext(){        return context;    }    public static Object getBean(String beanName) {        return context.getBean(beanName);    }}

擷取dao寫法

RuleDAO ruleDAO =(RuleDAO) ContextUtil.getBean("ruleDAO");                

 

 

使用線程池

StartTaskThread2.java

public class StartTaskThread implements Runnable {     private String st;        public StartTaskThread(String st) {       this.st= st;    }    @Override    public void run() {           System.out.println(st);    }}

線程池

RuleService2.java

@Servicepublic class RuleService {    public void updateRule(){        ThreadPoolTaskExecutor tpte =(ThreadPoolTaskExecutor)ContextUtil.getBean("threadPoolTaskExecutor");
        List<String> strList= new ArrayList<String>();        for (int i = 0; i < 2000; i++) {            strList.add("test"+i);        }        
        for (int i = 0; i < strList.size(); i++) {            tpte.execute(new StartTaskThread2(strList.get(i)));        }
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.