开发者

NSTimer interval less than sleep command in fired code

开发者 https://www.devze.com 2022-12-19 04:16 出处:网络
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.

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, an开发者_开发百科d not have to change the timer whenever I increase it over 0.5.

Or is there a better way to get this functionality?


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消