Search code examples
androidandroid-studiolibgdx

What's the best approach to run a task using Timer only 5 times?


I'm using LibGDX. I want to run a task 5 times only after a couple delay of seconds. I have 2 options.


Approach 1

Timer.schedule(new Task() {
        @Override
        public void run() {
            mytask();
        }
    }
    , 10
    , 10
    , 5
    );



Approach 2

Timer.schedule(new Task() { // 1st time
        @Override
        public void run() {
            mytask();
        }
    }
    , 10
    );
Timer.schedule(new Task() { // 2nd time
        @Override
        public void run() {
            mytask();
        }
    }
    , 10
    );
Timer.schedule(new Task() { // 3rd time
        @Override
        public void run() {
            mytask();
        }
    }
    , 10
    );
Timer.schedule(new Task() { // 4th time
        @Override
        public void run() {
            mytask();
        }
    }
    , 10
    );
Timer.schedule(new Task() { // 5th time
        @Override
        public void run() {
            mytask();
        }
    }
    , 10
    );




I think Approach 1 is more efficient but for some reason it does not stop after the 5th time, instead it keeps going on. Help.


Solution

  • The problem was that the LibGDX implementation of the Timer schedules the Task and than again x times as expressed in the last parameter. The comment of this method says says "Schedules a task to occur once after the specified delay and then a number of additional times at the specified interval." Therefore the first approach executes the Task 6 times and not as expected 5 times