Arnab
Arnab

Reputation: 50

What can I do to call a method after a definite interval of time repeatedly?

I am using libgdx and android studio. Here I am trying to call a method(for creating a texture) after a definite interval of time, 0.5seconds.but when I am running the program it's showing "not responding" dialogue.

private float x=System.currentTimeMillis();

//in update method


public void update(float dt) {

        handleinput();
        while(x<=System.currentTimeMillis()){
            eggs.create();
            //eggs.update(dt);
            x+=500;
         }
}

What to do?

Upvotes: 0

Views: 92

Answers (4)

quinz
quinz

Reputation: 1342

Your code is literally a running competition against the clock.

The loop is probably never ending because eggs.create() takes more time than the increment of 500 you do for x in the end of the cycle.

Also using float instead of long is not good practice.

EDIT: To have a proper scheduling use best known Java methods similar to what Florian S. is suggesting in his answer.

Upvotes: 0

Florian S.
Florian S.

Reputation: 442

You should use ExecutorService.scheduleAtFixedRate() or an Android equivalent for it when you want to run code cyclically. What you are doing will block the thread when egs.create() takes more than 500 ms.

Upvotes: 0

BaneDad
BaneDad

Reputation: 157

Your problem is you should not be using System.currentTimeMillis() here.

https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis() :

currentTimeMillis

Returns:the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

public void update(float dt) { 
    if(dt < 500) {
        int x = 10;
        // let x be some value to increment
        update(dt + x);
    }
    ...
}

This version will not guarantee half a second, but will give you a better idea as to how to tackle the problem.

Upvotes: 0

Hllink
Hllink

Reputation: 918

To handle time, use a variable adding delta time every time render is called, when this variable is superior a 1.0f means that one second has passed, your code would be something like this:

        private float timeSeconds = 0f;
        private float period = 1f;

        public void render() {
            //Execute handleEvent each 1 second
            timeSeconds +=Gdx.graphics.getDeltaTime();
            if(timeSeconds > period){
                timeSeconds-=period;
                handleEvent();
            }

            [...]

        }

        public void handleEvent() {
             [...]
        }

To keep organized i personally have an array on my main game class that holds all my timed events and process everything on the render cycle.

Upvotes: 1

Related Questions