GCD创建一个定时器

    xiaoxiao2021-12-13  19

    #pragma mark -

    #pragma mark   ==============定时器的开始和取消==============

    - (void)startStopData:(BOOL)isStart {

        if (isStart) {

            self.count =0;

                //获得队列

            dispatch_queue_t queue =dispatch_get_global_queue(0,0);

                //创建一个定时器

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

                //设置开始时间

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

                //设置时间间隔

            uint64_t interval = (uint64_t)(3.0*NSEC_PER_SEC);

                //设置定时器

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

                //设置回调

            dispatch_source_set_event_handler(self.timer, ^{

                    //在这里执行事件

                self.count +=3;

                if (self.count ==60) {

                    self.count =0;

                    [selfgetData];

                }

            });

               //由于定时器默认是暂停的所以我们启动一下

                //启动定时器

            dispatch_resume(self.timer);

        }else {

            if (self.timer) {

                dispatch_cancel(self.timer);

                self.timer =nil;

                self.count =0;

            }

        }

    }

    这是使用GCD创建的一个定时器的试用样例

    转载请注明原文地址: https://ju.6miu.com/read-950202.html

    最新回复(0)