Created
October 4, 2018 08:13
-
-
Save zerobranch/b507313145306fdfc7b4fc797f1f6e9f to your computer and use it in GitHub Desktop.
TimerUtils allows to start a timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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