user2885077
user2885077

Reputation: 712

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?

Upvotes: 1

Views: 2398

Answers (3)

trojanfoe
trojanfoe

Reputation: 122458

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.

Upvotes: 2

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

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.

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81878

NSTimers, 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.

Upvotes: 2

Related Questions