2

I am having a service in my application that puts a runnable (in another java file) in a thread and starts it. That is working fine for once, but i want it to be repetitive due to a certain period. I need a good way to handle that. Reason why I didn't use the answers to other questions is that I don't want it to repeat infinity nor I know how many times it'll repeat the task. It'll simply stop due to a button click in the UI.

I was thinking of using a loop with a sleep and if statement. But I think that's really bad design for my application. Is there a standard way for doing such thing?

Thanks...

user1347945
  • 493
  • 2
  • 7
  • 11

3 Answers3

4

You can use a handler that somehow acts like a timer but I think it is better for your situation.

You initialize it like this:

Handler delayhandler = new Handler();

Set the time it fires like this (in ms):

delayhandler.postDelayed(mUpdateTimeTask, 500);

And it calls this:

private Runnable mUpdateTimeTask = new Runnable()
{   public void run()
    {   // Todo

        // This line is necessary for the next call
        delayhandler.postDelayed(this, 100);
    }
}

You can also remove the next call with:

delayhandler.removeCallbacks(mUpdateTimeTask);
HardCoder
  • 3,026
  • 6
  • 32
  • 52
  • The problem is that I don't know how many times I will run it... Timers looks nicer – user1347945 May 02 '12 at 15:05
  • Thats the point, with a handler you have to explicitly say that you want to run it again or can just prevent it from running again anytime you want. Timers are messier. – HardCoder May 03 '12 at 04:27
1

Use a TimerTask and have it execute your thread/method.

http://android.okhelp.cz/timer-simple-timertask-java-android-example/

http://developer.android.com/reference/java/util/TimerTask.html - You can use the Cancel() method to stop the TimerTask from executing.

Gophermofur
  • 2,101
  • 1
  • 14
  • 14
  • Java timers run on separate threads, so this is a good approach. You don't even have to start one yourself. – DeeV May 01 '12 at 15:18
  • I guess this looks promising, but I got stuck in doing restarting the timer after cancelling... I get to error: "java.lang.IllegalStateException: Timer was canceled"... then i tried: myTimer.cancel(); myTimer = new Timer();, but I got the following error "java.lang.IllegalStateException: TimerTask is scheduled already"... I tried – user1347945 May 02 '12 at 15:00
0

Use the Timer it will run the thread after a given time period and when you want to stop just stop timer or set it to infinite time period.

Krishnakant Dalal
  • 3,568
  • 7
  • 34
  • 62