如何做一个定时器监听器?
How to do a timer listener?
我是 Java 的新手,我想制作一个程序,在检测到时间时执行确定的操作。
示例:
我启动一个计时器,当 30 段结束时,显示一条消息,3 分钟后,执行另一个动作,等等
我该怎么做?
谢谢
使用 ScheduledExecutorService 是一种可能。
见the docs for usage example and more。
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
使用定时器class,你可以这样做:
public void timer() {
TimerTask tasknew = new MyTask();
Timer timer = new Timer();
/* scheduling the task, the first argument is the task you will be
performing, the second is the delay, and the last is the period. */
timer.schedule(tasknew, 100, 100);
}
}
这是一个 class 的示例,它扩展了 TimerTask 并做了一些事情。
class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("Hello world from Timer task!");
}
}
如需进一步阅读,请查看
我是 Java 的新手,我想制作一个程序,在检测到时间时执行确定的操作。
示例: 我启动一个计时器,当 30 段结束时,显示一条消息,3 分钟后,执行另一个动作,等等
我该怎么做?
谢谢
使用 ScheduledExecutorService 是一种可能。
见the docs for usage example and more。
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
使用定时器class,你可以这样做:
public void timer() {
TimerTask tasknew = new MyTask();
Timer timer = new Timer();
/* scheduling the task, the first argument is the task you will be
performing, the second is the delay, and the last is the period. */
timer.schedule(tasknew, 100, 100);
}
}
这是一个 class 的示例,它扩展了 TimerTask 并做了一些事情。
class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("Hello world from Timer task!");
}
}
如需进一步阅读,请查看