在我的情况下,我创建了一个对象,并计划在20分钟后释放它(不需要精度)。我知道通过使用java.util.Timer
我可以创建一个计时器。但我只想让它运行一次。之后,计时器应该停止并释放。如何设置一个计时器,但不要重复运行
有没有什么办法就像在setTimeOut()
在JavaScript?
谢谢。
在我的情况下,我创建了一个对象,并计划在20分钟后释放它(不需要精度)。我知道通过使用java.util.Timer
我可以创建一个计时器。但我只想让它运行一次。之后,计时器应该停止并释放。如何设置一个计时器,但不要重复运行
有没有什么办法就像在setTimeOut()
在JavaScript?
谢谢。
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);
修改上面的内容以便将来可以安排20分钟的工作。
您可以启动一个新线程,并呼叫sleep
等待几毫秒,然后执行您的指令(在任一线程上)。请参阅http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html以供参考,如果您需要更多帮助,请参阅各种在线主题教程。
java.util.Timer
中有一个取消方法:
http://download.oracle.com/javase/6/docs/api/java/util/Timer.html#cancel%28%29
不过,据我所知,在计时器如果不指定周期,计划任务将只运行一次。
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);
}
}
这几乎是执行预定任务的最差方式。 –