Java定時任務實現

Java定時任務實現

由於工作中用到定時任務,在csdn首頁上又恰巧看到關於定時任務的文章,寫的不錯,本人只是抱着學習的態度!
     定時任務的實現:普通thread實現,TimerTask實現,ScheduledExecutorService實現
Thread方式實現:
public void threadWay(){
		final long timeInterval = 5000;
		Runnable run = new Runnable() {// 任務
			public void run() {
				while (true) {
					System.out.println("hello world!");
					try {
						Thread.sleep(timeInterval);
					}
					catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
		Thread thread = new Thread(run);
		thread.start();// 啓動Thread
}
這是最基礎的實現定時任務的方式!
TimerTask方式實現:
public void timeTaskWay(){
		TimerTask timeTask = new TimerTask(){
			public void run(){
				System.out.println("hello world");
			}
		};
		Timer time = new Timer();
		long delay = 10000;
		long intervalPeriod = 3*1000;
		time.scheduleAtFixedRate(timeTask, delay, intervalPeriod);
}
這種方式較高級,能夠設置delay(延遲時間),intervalPerid(運行間隔)
ScheduledExecutorService方式實現:
public void scheduledExecutorServiceWay() {
		Runnable run = new Runnable() {
			public void run() {
				System.out.println("hello world");
			}
		};
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.scheduleAtFixedRate(run, 0, 10, TimeUnit.SECONDS);
}
這種方式稍微高級點。
這是Java Application中,實現定時的任務的方式,如果使用的Spring可以用quartz實現,通過配置的實現,能夠設置更多的參數!
原文地址:http://blog.csdn.net/qq405371160/article/details/23696525

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章