I want to have a class that changes its own private variables every 2 seconds. I know that if I do something like
import java.util.Timer;
//...
Timer timer;
//...
timer.schedule(new ChangeSomething(), 2000);
It will execute ChangeSomething()
after 2 seconds, is there a way to tell it to do something every 2 seconds, or, If I put inside ChangeSomething()
timer.schedule(new ChangeSomething(), 2000);
will it work?
On a side-note, what does timer.cancel()
exactly do?
Here is an example
}
Use
timer.scheduleAtFixedRate()
to schedule it to recur every two seconds:From the javadoc for
Timer.cancel()
:EDIT:
Relating to internal execution thread for a
Timer
that executes a single task once:To be more precise here: ChangeSomething() is the constructor of your ChangeSomething class. The constructor will be executed immediately when you pass the ChangeSomething instace object to the timer, not after 2 seconds. It's that object's run() method will be triggered after 2 seconds.
To execute that run() method repeatedly all 2 seconds, use
schedule(TimerTask task, long delay, long period)
You will need to call to a different scheduling method of Timer, called scheduleAtFixedRate(...) which can get 3 parameters. The first 2 are identical to those of schedule you've used, while The third parameter indicates a period time in milliseconds between successive task executions.
You can check the java pai doc for this method here: http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask, java.util.Date, long)