使用java.util.Timer
并将回调传递给TimerTask
以安排下一次运行。cancel
如果需要,可以使用方法取消 TimerTask 。例如
package test;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTaskDemo {
private Timer timer = new Timer();
private MyTimerTask nextTask = null;
private interface Callback {
public void scheduleNext(long delay);
}
Callback callback = new Callback() {
@Override
public void scheduleNext(long delay) {
nextTask = new MyTimerTask(this);
timer.schedule(nextTask, delay);
}
};
public static class MyTimerTask extends TimerTask {
Callback callback;
public MyTimerTask(Callback callback) {
this.callback = callback;
}
@Override
public void run() {
// You task code
int delay = 1000;
callback.scheduleNext(delay);
};
}
public void start() {
nextTask = new MyTimerTask(callback);
timer.schedule(nextTask, 1000);
}
public static void main(String[] args) {
new TimerTaskDemo().start();
}
}