简体   繁体   English

如何在Java中添加循环计时器?

[英]How to add loop timer in Java?

How to loop this timer? 如何循环计时器? I want to print every 1 second. 我想每1秒打印一次。

Timer timer = new Timer();
timer = new Timer(false);
for (int i = 0; i < 10; i++) {
   timer.schedule(new TimerTask() {
      @Override
      public void run() {
         i--;
         System.out.println("Java " + i);
      }
   }, 0, 1000);
}

If it's really what you want, change 如果这确实是您想要的,请更改

}, 0, 1000);

to

}, 0, i * 1000);

And put i = 0 to i = 1 , and 11 not 10 or use <= 并把i = 0i = 1 11而不是10或使用<=

It will create and schedule a new TimerTask 10 times 它将创建并安排一个新的TimerTask 10次

Good way is to create your own TimerTask class. 好的方法是创建自己的TimerTask类。

In your Main class, you have this main method : 在您的Main类中,您具有以下main方法:

   public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new MyTimerTask(10), 1000, 1000);
    }

And then you only need create your own TimerTask class 然后,您只需要创建自己的TimerTask类

import java.util.TimerTask; 导入java.util.TimerTask;

public class MyTimerTask extends TimerTask {
    private int i2;
    public MyTimerTask(int i2){
        this.i2 = i2;
    }
    @Override
    public void run() {
        System.out.println("heej: " + i2);
    }    
}

This is outputing heej: 10 every second. 这将输出heej: 10每秒heej: 10次。


With your own class, you can control what is happeing there like this : 在您自己的班级中,您可以像这样控制快乐:

import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
    private int i2;
    private int count = 0;

    public MyTimerTask(int i2){
        this.i2 = i2;
    }
    @Override
    public void run() {
        count++;
        System.out.println("heej: " + i2);
        if (count > 10){
            this.cancel();            
        }
    }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM