2012-09-09 44 views
1
.... 

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.."); 

     } 
    } 
} 

我只在控制台中看到过一次“working ..”消息。我想看到每一秒都在“工作中......”代码上的问题是什么?而我的另一个问题是我想每秒运行一次自己的方法,但是如何?Java定时器不能正常工作

索里我的英文不好..

+0

你应该真正利用你的课程。 – vcapra1

回答

0

你需要在你的主线程等待被解雇的计时器。所有非守护线程完成后,JVM将退出。运行你的主要方法的线程实际上是唯一的非达恩线程,所以你应该等待,直到你的工作完成。

更改您的主要方法是这样的:

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. 
} 
+0

这仍然没有回答如何使任务重复的问题。 –

+0

从文档:'默认情况下,任务执行线程不作为守护进程线程运行,所以它能够保持应用程序不终止.'因此,这只适用于Timer构造函数Timer(布尔isDaemon)被使用。 –

+0

是的..我写这个很匆忙。为此事道歉。 –

7

Timer.schedule(TimerTask task, long delay)只运行一次的TimerTask毫秒的第二个参数的数量后。

周期运行的TimerTask,您需要使用其他schedule()重载如Timer.schedule(TimerTask task, long delay, long period)之一,例如:

time.schedule(calculate, 1000, 1000); 

该时间表,从现在起要执行的任务的1000毫秒,重复每1000毫秒。

+1

时间。计划(计算,0,1 * 1000);现在正常工作谢谢大家 – kibar

+0

+1真棒快速准确的响应......尽管您应该使用最新的API规范。 – oldrinb

1

您需要使用:

zaman.schedule(calculate, 0, 1000); 

安排定时运行一次以上。

1

它应该根据文档是一个时间:

公共无效时间表(TimerTask的任务, 长延迟)时刻表指定的延迟后执行指定的任务。参数:task - 任务计划为 。延迟 - 以毫秒为单位的任务执行前的延迟时间为 。抛出:IllegalArgumentException - 如果延迟为负数,或者延迟+ System.currentTimeMillis()为负数。 IllegalStateException - 如果任务已被调度或取消,或者定时器被取消。

你可能想打电话给

公共无效调度(TimerTask的任务, 长的延迟, 长周期)