Created
October 29, 2012 08:24
-
-
Save steve-taylor/3972330 to your computer and use it in GitHub Desktop.
DelayedTaskRunner
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.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import javax.swing.Timer; | |
/** | |
* Runs the last surviving task published after a specified delay. | |
* | |
* @author STaylor | |
*/ | |
public class DelayedTaskRunner { | |
private final Timer timer; | |
private Runnable task; | |
/** | |
* <p> | |
* Create a delayed task runner that runs the last task published | |
* that survives the duration of the specified delay. | |
* </p> | |
* <p> | |
* This class should be instantiated only from the Event Dispatch | |
* Thread. | |
* </p> | |
* | |
* @param delayMs The delay in milliseconds. | |
* @throws IllegalArgumentException if {@code delayMs < 0}. | |
*/ | |
public DelayedTaskRunner(final int delayMs) throws IllegalArgumentException { | |
if (delayMs < 0) { | |
throw new IllegalArgumentException("delayMs < 0"); | |
} | |
timer = new Timer(delayMs, new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
if (task != null) { | |
task.run(); | |
} | |
timer.stop(); | |
} | |
}); | |
} | |
/** | |
* <p> | |
* Set the task to be run and reset the timer so that the task | |
* will run after the configured delay if not overwritten by | |
* another task before the delay expires. | |
* </p> | |
* <p> | |
* Call this method from the Event Dispatch Thread. The specified | |
* task, if executed, will be executed in the Event Dispatch Thread. | |
* </p> | |
* | |
* @param task The task to potentially run. | |
*/ | |
public void setTask(final Runnable task) { | |
this.task = task; | |
timer.restart(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment