简体   繁体   中英

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

        }
    }
}

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..

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.

You need to use:

zaman.schedule(calculate, 0, 1000);

to schedule the timer to run more than once.

It is supposed to be one time according to the documentation:

public void schedule(TimerTask task, long delay) Schedules the specified task for execution after the specified delay. Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed. Throws: IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative. IllegalStateException - if task was already scheduled or cancelled, or timer was cancelled.

you probably want to call

public void schedule(TimerTask task, long delay, long period)

You need to wait in your main thread for the timer to be fired. The JVM will exit when all the non daemon threads are completed. The thread that runs your main method is actually the only non damon thread so you should make it wait until your work is complete.

Change your main method like this:

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

The version of Timer.schedule() which you are using only executes the task once after a delay. You need to use `Timer.schedule(TimerTask, long, long) to cause the task to repeat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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