==[[Java ScheduledExecutorService を利用してタイマーを実装]]==[[Java]{{category ] | [[Category:コード片}}]]
===Stopwatch.java===
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorServiceScheduledExecutorSer[[vi]]ce;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
// 15秒カウントしたら止める
if (chronometer.getPastSeconds() >>= 15) {
chronometer.stop();
}
*/
public static class Chronometer {
private ScheduledExecutorService ScheduledExecutorSer[[vi]]ce scheduler;
private long basetime;
private List<<TickListener> > listner; private ScheduledFuture<<?> > tickHandle;
public Chronometer() {
listner = new ArrayList<<TickListener>>();
scheduler = Executors.newScheduledThreadPool(1);
}
*/
public void start() {
final Runnable [[R]]unnable ticker = new Runnable[[R]]unnable() {
public void run() {
for (TickListener tl : listner) {
};
// 1秒ごとにイベントを発生
tickHandle = scheduler.scheduleAtFixedRatescheduleAtFixed[[R]]ate(ticker, 0, 1, TimeUnit.SECONDS);
}
/**
*/
public void stop() {
scheduler.schedule(new Runnable[[R]]unnable() {
public void run() {
tickHandle.cancel(true);