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.