[英]Java timer not working correctly
....
public class mainClass {
public mainClass(){
Timer time = new Timer();
mainClass.calculate calculate = new mainClass.calculate();
time.schedule(calculate, 1 * 1000);
}
public static void main(String[] args){
new mainClass();
}
class calculate extends TimerTask{
@Override
public void run() {
System.out.println("working..");
}
}
}
我在控制台中只看到一次“工作......”消息。我想看到每一秒“工作......”代码中的问题是什么? 而我的另一个问题是我想每秒运行我自己的方法但是如何?
索里因为我的英语不好..
Timer.schedule(TimerTask task, long delay)
仅在第二个参数中的毫秒数之后运行TimerTask一次。
要重复运行TimerTask,您需要使用其他schedule()
重载之一,例如Timer.schedule(TimerTask task, long delay, long period)
,例如:
time.schedule(calculate, 1000, 1000);
从现在开始计划1000毫秒执行任务,并每1000毫秒重复一次。
你需要使用:
zaman.schedule(calculate, 0, 1000);
安排计时器运行多次。
根据文档,它应该是一次:
public void schedule(TimerTask任务,长延迟)在指定的延迟后安排指定的任务执行。 参数:task - 要调度的任务。 延迟 - 执行任务之前的延迟(以毫秒为单位)。 抛出:IllegalArgumentException - 如果延迟为负,或者延迟+ System.currentTimeMillis()为负。 IllegalStateException - 如果已安排或取消任务,或者取消了计时器。
你可能想打电话
public void schedule(TimerTask任务,长延迟,长时间)
您需要在主线程中等待计时器被触发。 所有非守护程序线程完成后,JVM将退出。 运行main方法的线程实际上是唯一的非damon线程,所以你应该让它等到你的工作完成。
像这样改变你的主要方法:
public static void main(String[] args){
new mainClass();
Thread.sleep(2 * 1000); // wait longer than what the timer
// should wait so you can see it firing.
}
您正在使用的Timer.schedule()
版本仅在延迟后执行一次任务。 你需要使用`Timer.schedule(TimerTask,long,long)来重复任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.