TAGS :Viewed: 9 - Published at: a few seconds ago

[ Handling multiple TimerTasks with one Timer ]

With one TimerTask, everything looks pretty straightforward and works fine.
But I can not handle different 'TimerTasks' within one Timer. I tried adding TimerTask object into the constructor but have an compilation error when I pass new TimerTask (RemindTask1) object as a parameter (instance of inner class).

Here is how it works with one task:

public class MyTimer {
    Timer timer;

    public MyTimer(long time) {
        timer = new Timer();
        timer.schedule(new RemindTask(), time);
    }

    class RemindTask extends TimerTask {
        @Override
        public void run() {
            /// ...
            timer.cancel();
        }
    }

    public static void main(String[] args) {
        /// ...
        MyTimer myTimer = new MyTimer(5000);
        /// ...
    }
}

But I am completely stuck with how multiple tasks should be created and then run.

public class MyTimer {
    Timer timer;

    public MyTimer(TimerTask tt, long time) {
        timer = new Timer();
        timer.schedule(tt, time);
    }

    class RemindTask1 extends TimerTask {
        @Override
        public void run() {
            /// ...
            timer.cancel();
        }
    }

    class RemindTask2 extends TimerTask {
        @Override
        public void run() {
            /// ...
            timer.cancel();
        }
    }

    public static void main(String[] args) {
        /// ...
        MyTimer myTimer = new MyTimer(new RemindTask2(), 5000);
        /// ...
    }
}

But that's not working and I can't figure out what's wrong. I am having an compilation error when I pass new RemindTask2() as a parameter.

Answer 1


I assume by "not working" you mean the compiler isn't letting you create an instance of the inner class RemindTask2 from a static context (main method).

There are generally two ways to handle this.

  1. Ask a MyTimer instance to create its inner class instance for you. This actually isn't an option for you since you need the inner class instance to exist before you construct the MyTimer.
    MyTimer myTimer;
    // initialize myTimer
    TimerTask task = myTimer.new RemindTask2();
  1. Change the inner classes to nested classes by adding the static keyword. This is the option for you.
    static class RemindTask2 extends TimerTask {
        //...
    }