简体   繁体   中英

NSTimer as background thread

I need to ping a server at fixed intervals. I am currently using the following:

[NSTimer scheduledTimerWithTimeInterval:5.0f 
                                 target:[Socket getInstance] 
                               selector:@selector(sendHeartBeats) 
                               userInfo:nil 
                                repeats:YES];

This calls function sendHeartBeats at an interval of 5 sec.

Do i need to call this on a separate thread so that my main thread will not be affected?

NSTimer s, as well as the related NSRunLoop , do not affect (nor are aware of) the threading behavior of your process. Both just use the current thread.

This means that you have to care about threads on your own. NSTimer , in conjunction with NSRunLoop give you the opportunity to schedule timed tasks on a given thread.

You can use a timer on the main thread or start a new thread, add a runloop to it and start a timer on that background thread.

Anyway, when using threads, you have to be aware of thread safety issues. In this case this means making the Socket class (singleton?) thread safe because it is probably used elsewhere in your app.

Well to answer the question, the answer is "no" you don't need a background thread in order to avoid disrupting the main thread with a timer.

At least that's true of the NSTimer mechanism, however if the method that is called by the timer spends a lot of time doing something then the answer would "yes", you should call it in a background thread. However you are required to provide a runloop in that background thread in order for NSTimer to work, and then it gets complicated.

Therefore if I was going to do something in a background thread I would avoid NSTimer and simply do something like:

while (YES) {
    [[NSThread currentThread] sleepForTimeInterval:5.0];
    if ([[NSThread currentThread] isCancelled])
        break;
    doThing();
}

The thread that started this background thread would then call [thread cancel] in order to cancel that thread.

Do i need to call this on a separate thread so that my main thread will not be affected?

No need.

Timers work in conjunction with run loops. To use a timer effectively, you should be aware of how run loops operate—see NSRunLoop and Threading Programming Guide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM