3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

java Timer vs ScheduledExecutorService

Last updated at Posted at 2016-03-14

java Timer vs ScheduledExecutorService

▽:予定開始 ▼:実績開始

java.util.Timer.scheduleAtFixedRate


 予定:  ▽n-1  間隔 ▽n   間隔 ▽n+1  間隔 ▽n+2  間隔 ▽n+3  間隔 ▽n+4  
 実績:  ▼n-1  間隔 ▼n              ▼n+1 ▼n+2 ▼n+3  間隔 ▼n+4  

※:n回目の実行時間は長かった(お定の間隔時間を超える)場合   n+1回目からのタスクはn回目のタスクの実行完了を待ち、終了直後実行を開始する

---

java.util.Timer.schedule


 予定:  ▽n-1  間隔 ▽n   間隔 ▽n+1  間隔 ▽n+2  間隔 ▽n+3  間隔 ▽n+4  
 実績:  ▼n-1  間隔 ▼n              ▼n+1  間隔 ▼n+2  間隔 ▼n+3  

※:n回目の実行時間は長かった(お定の間隔時間を超える)場合   n+1回目のみのタスクはn回目のタスクの実行完了を待ち、終了直後実行を開始する

---

java.util.concurrent.ScheduledExecutorService.scheduleWithFixedDelay


 予定:  ▽n-1  間隔 ▽n   間隔 ▽n+1  間隔 ▽n+2  間隔 ▽n+3  間隔 ▽n+4  
 実績:  ▼n-1  間隔 ▼n               間隔 ▼n+1  間隔 ▼n+2  間隔  

※:n回目の実行時間は長かった(お定の間隔時間を超える)場合も n+1回目のみのタスクはn回目のタスクの実行完了を待ち、終了後、指定した間隔を空けて実行を開始する

---

例:

java.util.Timer
	TimerTask task = new TimerTask() {
	    @Override public void run() {
	    timeMessage("SCHEDULE start.");
	    timerRun(icon, args);
	    timeMessage("SCHEDULE end.");
	    }
	};
	
	Timer timer = new Timer();
scheduleAtFixedRate
    timer.scheduleAtFixedRate(task, 0, 1000 * 3);
schedule
    timer.schedule(task, 0, 1000 * 3);

java.util.concurrent.ScheduledExecutorService
	Runnable newTask = new Runnable() {
	    public void run() {
	    timeMessage("CONCURRENT start.");
	    timerRun(icon, args);
	    timeMessage("CONCURRENT end.");
	    }
	};
	
	scheduler = Executors.newSingleThreadScheduledExecutor();
scheduleWithFixedDelay
    scheduler.scheduleWithFixedDelay(newTask, 0, 3, TimeUnit.SECONDS );
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?