1. 程式人生 > >java 定時任務執行

java 定時任務執行

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * java 定時執行的實現
 * @author gzn
 */
public class InteveralTest {
	
	/**
	 * 測試執行緒
	 */
	public void ThreadTest(){
		final long timeInteveral = 1*1000;
		
		Runnable runable = new Runnable() {
			// 定義計數
			int count = 0;
			@Override
			public void run() {
				try{
					do{
						System.out.println("run " + count);
						count ++;
						if(10 == count){
							System.out.println("執行緒結束!");
							break;
						}
						// 執行緒沉睡1秒
						Thread.sleep(timeInteveral);
					}while(60 >= count);
				}catch(InterruptedException e){
					System.out.println(e);
				}
			}
		};
		// 執行緒初始化
		Thread thread = new Thread(runable);
		// 開始執行
		thread.start();
	}
	
	/**
	 * 測試定時任務
	 */
	public void TimerTest(){
		TimerTask task = new TimerTask() {
			int count = 0;
			@Override
			public void run() {
				System.out.println("TimerTask times : " + count);
				count++;
				if(10 == count){
					// 呼叫cancel方法執行緒終止,但資源未釋放
					this.cancel();
					// 呼叫系統gc方法進行資源回收,工程中不建議使用
					System.gc();
				}
			}
		};
		
		Timer timer = new Timer();
		// 任務執行前等待時間
		long delay = 0;
		// 執行間隔時間
		long period = 1*1000;
		timer.scheduleAtFixedRate(task, delay, period);
	}
	
	/**
	 * Scheduled
	 * @throws InterruptedException 
	 */
	public void ScheduledTest() throws InterruptedException{
		Runnable runable = new Runnable() {
			// 定義計數
			int count = 0;
			@Override
			public void run() {
				System.out.println("run " + count);
				count ++;
			}
		};
		
		ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor();
		/**
		 * Runnable command, 任務名
		 * long initialDelay, 等待時間
		 * long period, 間隔時間
		 * TimeUnit unit 入參時間型別
		 */
		scheduled.scheduleAtFixedRate(runable, 0, 1*1000, TimeUnit.MILLISECONDS);
		
		// 執行緒沉睡10秒
		Thread.sleep(10000);
		// 任務停止
		scheduled.shutdown();
	}
	
	/**
	 * 主執行緒每秒執行一次
	 * @throws InterruptedException
	 */
	public void MainThreadSleep() throws InterruptedException{
		// 標記(不常用)
		finish:
		for(int i = 0;i < 60;i++){
			if(i != 60){
				System.out.println("count : " + i);
				// 沉睡1秒
				Thread.sleep(1000);
				if(10 == i){
					break finish;
				}
			}
		}
	
		System.out.println("執行緒結束!");
	}
	
	public static void main(String[] args) throws InterruptedException {
		InteveralTest test = new InteveralTest();
		// 執行緒測試
//		test.ThreadTest();
		// timer定時任務測試
//		test.TimerTest();
		// 測試計劃任務
//		test.ScheduledTest();
		
		test.MainThreadSleep();
	}
	
}