0

I want my runnable to wait a couple of seconds before starting again, any advice on how to do this?

if i use this.wait(); it doesn't work because that stops everthing in my program and i just want the runnable to pause.

Sufian
  • 6,405
  • 16
  • 66
  • 120
Unskilled
  • 29
  • 5

3 Answers3

0

Here is an example for 2 second delayed Runnable

final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Do stuff

        handler.postDelayed(this, 2000);
    }
};

handler.postDelayed(runnable, 2000);
Niko
  • 8,093
  • 5
  • 49
  • 85
0

Hope this helps

Handler handler = new Handler();
final Runnable runner = new Runnable()
{
  public void run() 
   {
   //Restarts       
    handler.postDelayed(this, 1000);
  }
};

Thread thread = new Thread()
{
@Override
public void run() {
    try {
        while(true) {
            sleep(1000);
            handler.post(runner);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
};

thread.start();
LvN
  • 701
  • 1
  • 6
  • 22
0

It sounds that the main-thread is blocked in your example. See the example below. Here the main thread isn't blocked by calling wait.

public void onClick(View v) {
new Thread(new Runnable() {
    public void run() {
        try {
                synchronized (this) {
                    wait(1000); 
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
  }).start();
}

Look here is an example for threads: Android.com / processes and threads

Mr. Marco
  • 1
  • 2