代码之家  ›  专栏  ›  技术社区  ›  kibar

Java计时器工作不正常

  •  5
  • kibar  · 技术社区  · 14 年前
    ....
    
    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..");
    
            }
        }
    }
    

    我在控制台上只看到过一次“正在工作…”的消息。我想看到每一秒“正在工作..”代码有什么问题?我的另一个问题是,我想每秒钟都运行我自己的方法,但怎么办?

    对不起我英语不好。。

    5 回复  |  直到 14 年前
        1
  •  13
  •   Junyue Cao matt b    10 年前

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

    要重复运行TimerTask,您需要使用另一个 schedule() 过载,例如 Timer.schedule(TimerTask task, long delay, long period) ,例如:

    time.schedule(calculate, 1000, 1000);
    

    其调度从现在起1000毫秒要执行的任务并且每1000毫秒重复一次。

        2
  •  2
  •   roni bar yanai    14 年前

    根据文件,它应该是一次:

    公共无效调度(TimerTask任务, 长延迟)安排指定任务在指定延迟之后执行。参数:任务-要执行的任务 计划。delay—任务执行之前的延迟(以毫秒为单位) 已执行。抛出:IllegalArgumentException-如果延迟为负数,或者 delay+System.currentTimeMillis()为负数。非法状态例外 -如果任务已安排或取消,或者计时器已取消。

    你可能想打电话

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

        3
  •  1
  •   Reimeus    14 年前

    您需要使用:

    zaman.schedule(calculate, 0, 1000);
    

    以安排计时器运行多次。

        4
  •  1
  •   Mihai Toader    14 年前

    您需要在主线程中等待计时器启动。JVM将在所有非守护进程线程完成后退出。运行主方法的线程实际上是唯一的非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.
     }
    
        5
  •  0
  •   Code-Apprentice    14 年前

    的版本 Timer.schedule() 您正在使用的仅在延迟后执行任务一次。你需要使用 `Timer.schedule(TimerTask, long, long) 以使任务重复。