The easiest way I can come up with is to use Executor .
Suppose you want to schedule a task to run in 30 seconds:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.schedule(new Task(), 30, TimeUnit.SECONDS);
Task should be a class that implements the Runnable interface:
class Task implements Runnable { public void run() {
If you need to execute to stop the execution of your task, you can use the shutdownNow method:
// prevents task from executing if it hasn't executed yet scheduler.shutdownNow();
source share