Timers in Objective-C

Our first example demonstrates the use of timers in Objective-C. We’ll look at how to schedule code execution for the future or at regular intervals.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Timers represent a single event in the future. You
        // tell the timer how long you want to wait, and it
        // will execute a block after that time. This timer will wait 2 seconds.
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"Timer 1 fired");
        });
        
        // If you just wanted to wait, you could have used
        // [NSThread sleepForTimeInterval:]. One reason a timer may be useful is
        // that you can cancel it before it fires.
        // Here's an example of that.
        dispatch_source_t timer2 = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
        dispatch_source_set_timer(timer2, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), DISPATCH_TIME_FOREVER, 0);
        dispatch_source_set_event_handler(timer2, ^{
            NSLog(@"Timer 2 fired");
        });
        dispatch_resume(timer2);
        
        // Cancel the timer before it has a chance to fire
        dispatch_source_cancel(timer2);
        NSLog(@"Timer 2 stopped");
        
        // Give timer2 enough time to fire, if it ever was going to,
        // to show it is in fact stopped.
        [NSThread sleepForTimeInterval:2.0];
    }
    return 0;
}

In this Objective-C code:

  1. We use dispatch_after to create a timer that fires once after 2 seconds. This is similar to the time.NewTimer in the original example.

  2. We use a Grand Central Dispatch (GCD) timer (dispatch_source_t) to create a repeating timer. This is more flexible than the single-fire timer and can be cancelled, similar to the second timer in the original example.

  3. We cancel the second timer immediately after creating it, demonstrating how to stop a timer before it fires.

  4. We use [NSThread sleepForTimeInterval:] at the end to wait for 2 seconds, giving the second timer time to fire if it was going to.

To run the program, save it as Timers.m and compile it using:

$ clang -framework Foundation Timers.m -o Timers

Then run it:

$ ./Timers
Timer 2 stopped
Timer 1 fired

The output shows that Timer 1 fires after about 2 seconds, while Timer 2 is stopped before it has a chance to fire.