Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java timer not working correctly

Tags:

java

timer

....

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

        }
    }
}

I saw only one times "working.." message in the console.I want to saw every second "working.." whats the problem on code? and my another problem i want to running every second my own method but how?

Sory for my bad english..

like image 338
kibar Avatar asked Dec 07 '22 12:12

kibar


1 Answers

Timer.schedule(TimerTask task, long delay) only runs the TimerTask once, after the number of milliseconds in the second argument.

To repeatedly run the TimerTask, you need to use one of the other schedule() overloads such as Timer.schedule(TimerTask task, long delay, long period), for example:

time.schedule(calculate, 1000, 1000);

which schedules the task to be executed 1000 milliseconds from now, and to repeat every 1000 milliseconds.

like image 96
matt b Avatar answered Dec 31 '22 02:12

matt b