Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set an NSTimer to fire once in the future

How do I set up an NSTimer to fire once in the future (say, 30 seconds). So far, I have only managed to set it so it fires immediately, and then at intervals.

like image 692
cannyboy Avatar asked Oct 14 '11 08:10

cannyboy


3 Answers

The method you want to use is:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval) seconds target:(id) target selector:(SEL) aSelector userInfo:(id) userInfo repeats:(BOOL) repeats

with repeats == NO arguments and seconds == 30. This will create the timer and schedule it. It will fire only once, in 30 seconds (and not immediately).

like image 161
F'x Avatar answered Nov 08 '22 08:11

F'x


You can set the timer with your future date, and set repeats to NO

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval) seconds
                                     target:(id) target
                                   selector:(SEL) aSelector
                                   userInfo:(id) userInfo
                                    repeats:(BOOL) repeats
like image 37
JiteshW Avatar answered Nov 08 '22 09:11

JiteshW


Use this class method to schedule timer.

 +(NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
    target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo
    repeats:(BOOL)repeats

Parameters
seconds
The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead.
target
The object to which to send the message specified by aSelector when the timer fires. The target object is retained by the timer and released when the timer is invalidated.
aSelector
The message to send to target when the timer fires. The selector must have the following signature:
- (void)timerFireMethod:(NSTimer*)theTimer
The timer passes itself as the argument to this method.
userInfo
The user info for the timer. The object you specify is retained by the timer and released when the timer is invalidated. This parameter may be nil.
repeats
If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
Example

    [NSTimer scheduledTimerWithTimeInterval:2.0
             target:self
             selector:@selector(targetMethod:)
             userInfo:[self userInfo]
             repeats:NO];

The timer is automatically fired by the run loop after 2 seconds. Timer Programming Topics

like image 23
Parag Bafna Avatar answered Nov 08 '22 09:11

Parag Bafna