Reputation: 4245
In my case I created a object and planned to release it after 20 minutes(accuracy is not necessary). I know by using java.util.Timer
I can create a timer.But I just want it run once. After that,the timer should stop and been released too.
Is there any way just like setTimeOut()
in javascript?
Thanks.
Upvotes: 0
Views: 121
Reputation: 2674
package com.stevej;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class StackOverflowMain {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable myAction = new Runnable() {
@Override
public void run() {
System.out.println("Hello (2 minutes into the future)");
}
};
executor.schedule(myAction, 2, TimeUnit.MINUTES);
}
}
Upvotes: 0
Reputation: 78013
Use Timer::schedule(TimerTask, long)
or look into the ScheduledThreadPoolExecutor
or ScheduledExecutorService
classes.
Upvotes: 2
Reputation: 2501
java.util.Timer
has a cancel method in it:
http://download.oracle.com/javase/6/docs/api/java/util/Timer.html#cancel%28%29
However, as far as I know, in timer if you do not specify a period, scheduled task will run only once.
Upvotes: 0
Reputation: 1655
int numberOfMillisecondsInTheFuture = 10000; // 10 sec
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// Task here ...
}
}, timeToRun);
Modify above so that you can schedule a job 20 minutes in future.
Upvotes: 3
Reputation: 225074
You can start a new thread and call sleep
with the number of milliseconds to wait, then execute your instructions (on either thread). See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html for reference, and look at the various online thread tutorials if you need more help.
Upvotes: 0