Created
July 3, 2012 21:55
-
-
Save janodev/3043614 to your computer and use it in GitHub Desktop.
timer with dispatch source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef void (^loop_work_t)(void); | |
@interface TaxiLoop : NSObject | |
@property (nonatomic,assign) loop_work_t block; | |
@property (nonatomic,assign) NSTimeInterval interval; | |
@property (nonatomic,assign) dispatch_source_t timerSource; | |
-(id) initWithInterval:(NSTimeInterval)seconds block:(loop_work_t)block; | |
-(void) start; | |
-(void) stop; | |
@end | |
#import "TaxiLoop.h" | |
@implementation TaxiLoop | |
@synthesize interval=_interval; | |
@synthesize block=_block; | |
@synthesize timerSource=_timerSource; | |
-(id) initWithInterval:(NSTimeInterval)seconds block:(loop_work_t)block | |
{ | |
if (self = [super init]){ | |
self.interval = seconds; | |
self.block = block; | |
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); | |
dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, backgroundQueue); | |
dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), seconds*NSEC_PER_SEC, 0*NSEC_PER_SEC); | |
dispatch_source_set_event_handler(timerSource, ^{ | |
block(); | |
}); | |
self.timerSource = timerSource; | |
} | |
return self; | |
} | |
-(void) start { | |
dispatch_resume(self.timerSource); | |
debug(@"Taxi update started."); | |
} | |
-(void) stop { | |
dispatch_suspend(self.timerSource); | |
debug(@"Taxi update stopped."); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment