1

I would like to know where is the problem in this class, I'm making a class that every n seconds make something, but it appear to do it only 1 time. this is the class

import java.util.Timer;
import java.util.TimerTask;

public class Updater {
    private Timer timer;
    public Updater(int seconds){
        timer = new Timer();
        timer.schedule(new UpdaterTask(), seconds*1000);
    }
    class UpdaterTask extends TimerTask {
        public void run() {
            System.out.println(Math.random());
            timer.cancel();
        }
    }
}

and this is the test

public class TestUpdater {
    public static void main(String[] args){
        new Updater(1);
    }
}

i think that this test have to give me a random number every second but after the first second the process terminate. Sorry for the bad english and thanks for any suggestion

Dariusz
  • 21,561
  • 9
  • 74
  • 114
Oxenarf
  • 200
  • 6
  • 23

3 Answers3

0

When your main() thread terminates the application also terminates.

Just add Thread.sleep(10000) at the end of your code. It will then work for 10 seconds.

AND

Consult this answer for how to use the cancel method. I think you did not want to use it there.

AND

Change the scheduling type, use

timer.scheduleAtFixedRate(new UpdaterTask(), 0, seconds*1000);

Community
  • 1
  • 1
Dariusz
  • 21,561
  • 9
  • 74
  • 114
0
  1. schedule(task, delay) only execute the task once. schedule(task, delay, period) execute the task repeatedly with fixed delay.

    timer.schedule(new UpdaterTask(), 0, seconds * 1000)
    
  2. Remove cancel()

    // timer.cancel();
    
johnchen902
  • 9,531
  • 1
  • 27
  • 69
0

You need to comment out, the timer.cancel() call. This is making the timer itself stop after the first execution of its timer task.

Then for repeated execution, you should call scheduleAtFixedRate method, with delay == 0, to start the task immediately, and period == x seconds, to run it every x seconds.

class Updater {
    private Timer timer;
    public Updater(int seconds){
        timer = new Timer();
        timer.scheduleAtFixedRate(new UpdaterTask(), 0, seconds*1000); // use scheduleAtFixedRate method
    }
    class UpdaterTask extends TimerTask {
        public void run() {
            System.out.println(Math.random());
            //timer.cancel(); --> comment this line
        }
    }
}
sanbhat
  • 17,522
  • 6
  • 48
  • 64