我正在使用计时器实用程序重复发布代码输出。现在我将它设置为以1秒的间隔重复不间断。如何更改此内容而不是重复,直到达到用户设置的时间限制?
//Create a new timer
Timer timer = new Timer();
static int interval = 1000; //Interval of timer in milliseconds
//Set the timer to start in 1 second and to go every certain amount of milliseconds.
timer.scheduleAtFixedRate(TimerClass.timertask, 1000, interval);
答案 0 :(得分:0)
正如MadProgrammer所说;这可以通过使用TimerTask.cancel
方法中的TimerTask.run
方法来实现。
例如:
public class RunUntilInstantTimerTask extends TimerTask {
private final Instant stopTime;
public RunUntilInstantTimerTask(final Instant stopTime) {
this.stopTime = Objects.requireNonNull(stopTime);
}
@Override
public void run() {
// Do scheduled stuff...
if (Instant.now().isAfter(this.stopTime)) {
this.cancel();
}
}
}