Skip to content

Instantly share code, notes, and snippets.

@steve-taylor
Created October 29, 2012 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steve-taylor/3972330 to your computer and use it in GitHub Desktop.
Save steve-taylor/3972330 to your computer and use it in GitHub Desktop.
DelayedTaskRunner
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