views:

236

answers:

1

I have a snippet of code I want to execute repeatedly, but with the ability to pause and resume it. To do this, I have utilised an NSTimer, which I can stop and start as required.

Within the snippet, I use a sleep command to wait for something to update (0.3 seconds). The timer is firing every 0.5 seconds.

What would be ideal is to keep the stop and start functionality, and be firing every 0.3 seconds, but to not have to explicitly say I want it to fire every x seconds. The 0.5 is completely arbitrary, and is just set to be > 0.3.

If I set the timer to fire every 0.01 seconds, but keep the sleep command within the code fired to 0.3 seconds, will I get the desired behaviour? Or will the timer back up all the events, with unexpected results (for example multiple firings after I have stopped it)? This way I could make the 0.3 sec sleep a variable, and not have to change the timer whenever I increase it over 0.5.

Or is there a better way to get this functionality?

A: 

One of the biggest problems with this I see is that NSTimer will be consuming time on whatever thread it's registered with.

In most cases for me this is my main thread, sleeping inside of your main thread would be a bad thing as far as I can see.

A few alternative designs that may be better for you.

  1. Don't sleep. Have the selector called by the timer do a 'am I paused' check and exit early if it is.

  2. Invalidate the NSTimer when pausing and recreate it when unpausing (Note: you can't just reschedule the old timer).

  3. Spawn a background thread with it's own RunLoop or even your own while loop that just handles the rescheduling with sleeping.

Those are also roughly in the order I'd do them, as No. 1 seems the cleanest to me, followed by No.2. No.3 while viable could introduce a lot of potential nastiness (threading issues, clean shutdowns, etc)

Bryan McLemore
Thanks Bryan.No. 2. is what I'm doing currently. But using the NSTimer means I MUST have an interval, and that interval can't be less than the sleep in the selector.Not sure I understand number 1. The sleep is to allow something non-programatic to complete, which I have no way of knowing when it's done, so would this rule it out?Interested in no. 3. So instead of a timer, I could just keep an infinite loop going, that checks a boolean on entry, and to 'pause' the loop I just switch that bool? And to start up again, I would need to revert the bool back and fire the loop again?
Ben Packard