java-並發-定時任務ScheduleExecutorService和spring用法


一. ScheduleExecutorService配置

說明
注意問題:

  • 我們需要捕獲最上層的異常,防止出現異常中止執行,導致周期性的任務不再執行。
  • 如果執行的任務大於我們指定的執行間隔,比如scheduleAtFixedRate方法;當執行任務的時間大於我們指定的間隔時間時,等待任務執行完畢,再開啟新的線程;

方法區別

  • scheduleAtFixedRate從上一個任務開始計算,頻率固定;
  • scheduleWithFixedDealy從上一個任務結束時開始計算,頻率不固定;

scheduleAtFixedRate

    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,		//執行線程
                                                  long initialDelay,	//初始化延遲
                                                  long period,			//兩次執行最小間隔
                                                  TimeUnit unit);		//計時單位

scheduleWithFixedDelay

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  	//執行線程
                long initialDelay,  			//初始化延時
                long delay,  					//前一次執行結束到下一次執行開始的間隔時間(間隔執行延遲時間)
                TimeUnit unit);  				//

使用例子
例子1:以固定周期頻率執行任務

public static void executeFixedRate() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
    executor.scheduleAtFixedRate(  
            new EchoServer(),  
            0,  
            100,  
            TimeUnit.MILLISECONDS);  
}  

例子2:以固定延遲時間進行執行

public static void executeFixedDelay() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
    executor.scheduleWithFixedDelay(  
            new EchoServer(),  
            0,  
            100,  
            TimeUnit.MILLISECONDS);  
}  

例子3:每天晚上8點執行一次,每天定時安排任務進行執行

public static void executeEightAtNightPerDay() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
    long oneDay = 24 * 60 * 60 * 1000;  
    long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  
    initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
  
    executor.scheduleAtFixedRate(  
            new EchoServer(),  
            initDelay,  
            oneDay,  
            TimeUnit.MILLISECONDS);  
} 

//獲取指定時間對應的毫秒數
private static long getTimeMillis(String time) {  
    try {  
        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
        return curDate.getTime();  
    } catch (ParseException e) {  
        e.printStackTrace();  
    }  
    return 0;  
} 

任務代碼如下

class EchoServer implements Runnable {  
    @Override  
    public void run() {  
        try {  
            Thread.sleep(50);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        System.out.println("This is a echo server. The current time is " +  
                System.currentTimeMillis() + ".");  
    }  
} 

二. Spring配置

除了我們自己實現定時任務之外,我們可以使用Spring幫我們完成這樣的事情。

<bean id="myTimedTask" class="com.study.MyTimedTask"/> 
<bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
    <property name="targetObject" ref="myTimedTask"/>  
    <property name="targetMethod" value="execute"/>  
    <property name="concurrent" value="false"/>  
</bean>  
<bean id="myTimedTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
    <property name="jobDetail" ref="doMyTimedTask"/>  
    <property name="cronExpression" value="0 0 2 * ?"/>  
</bean>  
<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
    <property name="triggers">  
        <list>  
            <ref local="myTimedTaskTrigger"/>  
        </list>  
    </property>  
</bean> 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM