Skip to content

Instantly share code, notes, and snippets.

@zerobranch
Created October 4, 2018 08:13
Show Gist options
  • Save zerobranch/b507313145306fdfc7b4fc797f1f6e9f to your computer and use it in GitHub Desktop.
Save zerobranch/b507313145306fdfc7b4fc797f1f6e9f to your computer and use it in GitHub Desktop.
TimerUtils allows to start a timer
import java.util.Timer;
import java.util.TimerTask;
public class TimerUtils {
private TimerTask timerTask;
private Timer timer;
private Action action;
public void start(Action action, int delay) {
this.action = action;
if (timer != null) {
timer.cancel();
timerTask.cancel();
}
timer = new Timer();
timerTask = new CustomTimerTask();
timer.schedule(timerTask, delay);
}
public void stop() {
if (timer != null) {
timer.cancel();
timerTask.cancel();
timer.purge();
}
timer = null;
timerTask = null;
action = null;
}
public void safeStop() {
if (timer != null) {
timer.cancel();
timerTask.cancel();
timer.purge();
}
if (action != null) {
action.invoke();
}
timer = null;
timerTask = null;
action = null;
}
private class CustomTimerTask extends TimerTask {
@Override
public void run() {
if (action != null) {
action.invoke();
}
}
}
public interface Action {
void invoke();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment