Reputation: 1487
Suppose I have a class that looks something like this:
import javax.swing.*;
import java.util.*;
public class MyClass extends JFrame
{
private java.util.Timer timer = new java.util.Timer();
...
private class MyTimerTask extends TimerTask
{
@Override
public void run()
{
doStuff();
if (conditionIsMet())
{
timer.schedule(new MyTimerTask(), 1000);
}
else
{
timer.schedule(new MyTimerTask(), 500);
}
}
}
}
Now I have always thought of the run method of a TimerTask
somewhat like a loop. It runs once, then, if you want to run it again you can do so by calling schedule
. So my question is: When I call timer.schedule()
does it execute any other code in the TimerTask
or does it act as if I used break
in a loop? If I wrote the method like this instead:
@Override
public void run()
{
doStuff();
if (conditionIsMet())
{
timer.schedule(new MyTimerTask(), 1000); // method wouldn't end after this call
}
timer.schedule(new MyTimerTask(), 500);
}
Would it function the same?
Upvotes: 0
Views: 280
Reputation: 8938
Scheduling a timer task is just a method call; it does not cause the current execution of the timer task's run() method to end, so no, the two code examples do not function the same. It's better practice to use the first of your two code examples, scheduling the task only once in the run method.
Upvotes: 2