美文网首页
GCD定时器

GCD定时器

作者: 佐鼬_1282 | 来源:发表于2020-04-21 11:15 被阅读0次

@property (nonatomic, strong) dispatch_source_t timer;//定义全局变量,否则局部变量会销毁,导致无法回调

    dispatch_queue_t queue = dispatch_get_main_queue();

    // 创建一个定时器(dispatch_source_t本质还是个OC对象)

    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    // 设置定时器的各种属性(几时开始任务,每隔多长时间执行一次)

    // GCD的时间参数,一般是纳秒(1秒 == 10的9次方纳秒)

    // 何时开始执行第一个任务

    // dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC) 比当前时间晚3秒

    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));

    uint64_tinterval = (uint64_t)(1.0*NSEC_PER_SEC);

    dispatch_source_set_timer(self.timer, start, interval,0);

    // 设置回调

    dispatch_source_set_event_handler(self.timer, ^{

        NSLog(@"每秒执行test");

    });

    // 启动定时器

    dispatch_resume(self.timer);

相关文章

网友评论

      本文标题:GCD定时器

      本文链接:https://www.haomeiwen.com/subject/fhhyvhtx.html