I need help understanding the scheduleAtFixedRate method of theTimer class in java
java, syntax
Solution
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}, delay, period);
That code is equivalent to this refactoring, where the `new TimerTask` is assigned to a local variable.
TimerTask task = new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
};
timer.scheduleAtFixedRate(task, delay, period);
Of course the weird part has just moved upwards a bit. What is this `new TimerTask` stuff, exactly?
Java has special syntax for defining anonymous inner classes. Anonymous classes are a syntactical convenience. Instead of defining a sub-class of `TimerTask` elsewhere you can define it and its `run()` method right at the point of usage.
The code above is equivalent to the following, with the anonymous `TimerTask` sub-class turned into an explicit named sub-class.
class MyTimerTask extends TimerTask
{
public void run()
{
System.out.println(setInterval());
}
}
TimerTask task = new MyTimerTask();
timer.scheduleAtFixedRate(task, delay, period);
Problem
Being a fan of the Pomodoro technique I'm making myself a countdown timer to keep me on task with my homework. This particular project, however, is NOT homework. :) Stack has a LOT of questions about using timers to control delays before user input and the like, but not a lot on standalone timers. I've run across this code from a friend, and have studied the class on Java Documentation. ``` public class Stopwatch { static int interval; static Timer timer; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input seconds => : "); String secs = sc.nextLine(); int delay = 1000; int period = 1000; timer = new Timer(); interval = Integer.parseInt( secs ); System.out.println(secs); timer.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println(setInterval()); } }, delay, period); } private static final int setInterval() { if( interval== 1) timer.cancel(); return --interval; } } ``` There is some syntax that's not clear to me. Consider: ``` timer.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println(setInterval()); } }, delay, period); ``` I'm not understanding how the parentheses and braces work. At first glance, given the usage of `scheduleAtFixedRate(TimerTask task, long delay, long period)` I can see the `delay` and `period` parameters, but not an open paren preceding first parameter. Is my first parameter actually this whole block of code? I would expect the whole block to be surrounded by parentheses...but it's not. Is this a common syntax in java? I've never run across it before. new TimerTask() { public void run() { System.out.println(setInterval()); } } I just want to clarify that I understand it before I start mucking about with changes.