GCD定時(shí)器不受RunLoop影響裂七,比NSTimer更精確
//獲得隊(duì)列
//dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_queue_t queue =dispatch_get_main_queue();
//創(chuàng)建一個(gè)定時(shí)器(dispatch_source_t本質(zhì)還是個(gè)OC對象)需要強(qiáng)引用
self.timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
//設(shè)置定時(shí)器的各種屬性(幾時(shí)開始任務(wù)狡孔,每隔多長時(shí)間執(zhí)行一次)
// GCD的時(shí)間參數(shù),一般是納秒(1秒== 10的9次方納秒)
//何時(shí)開始執(zhí)行第一個(gè)任務(wù)
// dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC)比當(dāng)前時(shí)間晚3秒
dispatch_time_t start =dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0*NSEC_PER_SEC));
uint64_t interval = (uint64_t)(1.0*NSEC_PER_SEC);
dispatch_source_set_timer(self.timer, start, interval,0);
//設(shè)置回調(diào)
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"------------%@", [NSThreadcurrentThread]);
count++;
//if (count == 4) {
////取消定時(shí)器
//dispatch_cancel(self.timer);
//self.timer = nil;
//}
});
//啟動定時(shí)器
dispatch_resume(self.timer);