##Creating a timer with Grand Central Dispatch
At the following is the implementation file of a sample class that shows, how to make a timer with the help of Grand Central Dispatch. The timer fires on a global queue, just change the queue to the main queue or any custom queue and the timer fires on this queue and not on the global queue anymore.
#import <Foundation/Foundation.h>
@interface SampleClass : NSObject
- (void)startTimer;
- (void)cancelTimer;
@end
#import "SampleClass.h"
dispatch_source_t CreateDispatchTimer(double interval, dispatch_queue_t queue, dispatch_block_t block)
{
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (timer)
{
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, interval * NSEC_PER_SEC), interval * NSEC_PER_SEC, (1ull * NSEC_PER_SEC) / 10);
dispatch_source_set_event_handler(timer, block);
dispatch_resume(timer);
}
return timer;
}
@implementation SampleClass {
dispatch_source_t _timer;
}
- (void)startTimer
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
double secondsToFire = 1.000f;
_timer = CreateDispatchTimer(secondsToFire, queue, ^{
// Do something
});
}
- (void)cancelTimer
{
if (_timer) {
dispatch_source_cancel(_timer);
// Remove this if you are on a Deployment Target of iOS6 or OSX 10.8 and above
dispatch_release(_timer);
_timer = nil;
}
}
@end