I need help understanding the scheduleAtFixedRate method of theTimer class in java

13,288

Solution 1

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);

Solution 2

You are correct, the first parameter is the entire code block:

new TimerTask()
{
     public void run()
     {
          System.out.println(setInterval());
     }
}

These declarations are called Anonymous classes and are explained in more detail in the Java Tutorials.

Solution 3

It is a anonymous inner class. You need to study inner classes for understanding this. Generally such classes are used when you do not need the class to be used else where in your code. You cannot use it else where just because you dont have reference pointing to it. You can also replace the above code as follows :

class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            // Timer task code goes here.
             System.out.println(setInterval());
        }

    }
    MyTimerTask timerTask = new MyTimerTask();
    timer.scheduleAtFixedRate(timerTask, delay, period);
Share:
13,288
dwwilson66
Author by

dwwilson66

Visual Communications Professional with a background in technology. In the thick of learning Java, PHP & MySQL to augment my web skills. I'm taking a shine to programming a lot more than I thought I would.

Updated on June 04, 2022

Comments

  • dwwilson66
    dwwilson66 almost 2 years

    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.

  • dwwilson66
    dwwilson66 about 11 years
    Fantastic! Thanks also for what they're called so I know what to look for in the tutorials. :)
  • Keppil
    Keppil about 11 years
    @dwwilson66: You're welcome. Don't forget to upvote helpful answers, and mark the best one as accepted if you are satisfied.