ScheduledExecutorService定時周期執行指定的任務


示例代碼
package com.effective.common.concurrent.execute;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Schedule {
	
	private static DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
	private static DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
	
	private static ScheduledExecutorService excutor = Executors.newSingleThreadScheduledExecutor();
	
	/**
	 * 按指定頻率周期執行某個任務 <br>
	 * 初始化延遲0ms開始執行,每隔5ms重新執行一次任務。
	 */
	public void fixedRate(){
		excutor.scheduleAtFixedRate(new EchoServer(), //執行線程
									0,  //初始化延遲
									5000, //兩次開始的執行的最小時間間隔
									TimeUnit.MILLISECONDS //計時單位
									);
	}
	
	/**
	 * 
	 */
	public void fixDelay(){
		excutor.scheduleWithFixedDelay(new EchoServer(),//執行線程 
				0, //初始化延遲
				5000, //前一次執行結束到下一次執行開始的間隔時間
				TimeUnit.MILLISECONDS);
	}
	
	/**
	 * 每天晚上8點執行一次
	 */
    public void dayOfDelay(String time){
        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); 
    }
    
        
    /**
     * 獲取給定時間對應的毫秒數
     * @param string "HH:mm:ss"
     * @return
     */
	private static long getTimeMillis(String time) {        
        try {
			Date currentDate = dateFormat.parse(dayFormat.format(new Date()) + " " +time);
			return currentDate.getTime() ;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static void main(String[] args){
		
		Schedule schedule = new Schedule();
		schedule.fixedRate();
		schedule.fixDelay();
		
	}
    
}


免責聲明!

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



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