タイマー
Java
方法1:java.util.Timerとjava.util.TimerTask
サンプル
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// do something
}
}, 5 * 1000); // 5秒後に実行 一回だけ
new Timer().schedule(new TimerTask(){
@Override
public void run() {
// do something
}
}, 5 * 1000, 3 * 1000); // 5秒後から3秒おきに実行
応用例
★カウントダウン
final Timer timer = new Timer();
final long end = System.currentTimeMillis() + 1000 * 10; // 10秒後
timer.schedule(new TimerTask() {
@Override
public void run() {
long show = end - System.currentTimeMillis();
long h = show / 1000 / 60 / 60;
long m = show / 1000 / 60 % 60;
long s = show / 1000 % 60;
System.out.println(h + ":" + m + ":" + s);
}
}, 0, 1000); // 1秒おき
timer.schedule(new TimerTask() {
@Override
public void run() {
timer.cancel(); // タイマーを停止
}
}, new Date(end));
★目覚まし
// 明日の朝7時を設定
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.HOUR_OF_DAY, 7);
cal.add(Calendar.MINUTE, 0);
cal.add(Calendar.SECOND, 0);
java.util.Date start = cal.getTime();
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// do something
}
}, start, 1000L * 60 * 60 * 24); // 24時間おき
★タイムアウト
FutureTask<MyResult> timeoutTask = null;
try {
timeoutTask = new FutureTask<MyResult>(new Callable<MyResult>() {
@Override
public MyResult call() throws Exception {
MyResult result = ...; // Expensive operation
return result;
}
});
new Thread(timeoutTask).start();
MyResult result = timeoutTask.get(5L, TimeUnit.SECONDS);
...
} catch (InterruptedException e) {
...
} catch (ExecutionException e) {
...
} catch (TimeoutException e) {
// After 5 seconds, time expires
}
import java.util.concurrent.TimeUnit;
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(4));
Thread.sleep(4 * 60 * 1000);
TimeUnit.MINUTES.sleep(4);
} catch (InterruptedException e) {
Thread.interrupted();
throw new IllegalStateException(e);
}
final long start = System.nanoTime();
...
final long end = System.nanoTime();
final long total =
TimeUnit.NANOSECONDS.toSeconds(end - start);
方法2:java.util.concurrent.ScheduledExecutorService(推奨)
ScheduledExecutorService scheduler
= Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<Object> future
= scheduler.schedule(task, 1, TimeUnit.SECONDS);
future.get(); // エラー時にExecutionException
future.cancel();