Code cleanup: cleanup timer usage in TimerTaskExecutor

This commit is contained in:
Jimmy Shih
2013-06-13 12:39:40 -07:00
parent 9d6ff995f7
commit 0b75c95e93
@@ -33,10 +33,7 @@ public class TimerTaskExecutor {
private final PeriodicTask periodicTask; private final PeriodicTask periodicTask;
private final TrackRecordingService trackRecordingService; private final TrackRecordingService trackRecordingService;
/** private TimerTask timerTask;
* A timer to schedule the announcements. This is non-null if the task is in
* started (scheduled) state.
*/
private Timer timer; private Timer timer;
public TimerTaskExecutor(PeriodicTask periodicTask, TrackRecordingService trackRecordingService) { public TimerTaskExecutor(PeriodicTask periodicTask, TrackRecordingService trackRecordingService) {
@@ -50,6 +47,10 @@ public class TimerTaskExecutor {
* @param interval the interval in milliseconds * @param interval the interval in milliseconds
*/ */
public void scheduleTask(long interval) { public void scheduleTask(long interval) {
if (interval <= 0) {
return;
}
if (!trackRecordingService.isRecording() || trackRecordingService.isPaused()) { if (!trackRecordingService.isRecording() || trackRecordingService.isPaused()) {
return; return;
} }
@@ -59,43 +60,32 @@ public class TimerTaskExecutor {
return; return;
} }
if (timer != null) { shutdown();
timer.cancel(); periodicTask.start();
timer.purge(); timerTask = new TimerTask() {
} else { @Override
// First start, or we were previously shut down. public void run() {
periodicTask.start(); periodicTask.run(trackRecordingService);
} }
};
timer = new Timer(); timer = new Timer();
if (interval <= 0) {
return;
}
long next = System.currentTimeMillis() + interval - (tripStatistics.getTotalTime() % interval); long next = System.currentTimeMillis() + interval - (tripStatistics.getTotalTime() % interval);
timer.scheduleAtFixedRate(new PeriodicTimerTask(), new Date(next), interval); timer.scheduleAtFixedRate(timerTask, new Date(next), interval);
} }
/** /**
* Shuts down. * Shuts down.
*/ */
public void shutdown() { public void shutdown() {
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
if (timer != null) { if (timer != null) {
timer.cancel(); timer.cancel();
timer.purge(); timer.purge();
timer = null; timer = null;
periodicTask.shutdown();
}
}
/**
* The timer task to announce the trip status.
*/
private class PeriodicTimerTask extends TimerTask {
@Override
public void run() {
periodicTask.run(trackRecordingService);
} }
periodicTask.shutdown();
} }
} }