美文网首页
iOS 定时器

iOS 定时器

作者: 青椒辣不辣 | 来源:发表于2020-12-18 17:22 被阅读0次

\color{rgb(0 ,139, 139)}{swift 倒计时-GCD}

    private var timer: DispatchSourceTimer?

    func startTimeOut(expireTime: String) {
        let current = NSDate.getNowTimeMillisecondTimestamp() ?? ""
        let aaa = (Double(expireTime) ?? 0) / 1000
        let bbb = (Double(current) ?? 0) / 1000
        var timeOut =  Int(aaa - bbb)
        
        if timer != nil {
            timer?.cancel()
            timer = nil;
        }
        timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        timer?.schedule(deadline: .now(), repeating: .seconds(1))
        timer?.setEventHandler {
            if timeOut <= 0 {
                self.timer?.cancel()
                DispatchQueue.main.async { self.timeOutSuccess?() }
            }else{
                DispatchQueue.main.async {
                    let h = timeOut / 3600
                    let minutes = timeOut % 3600 / 60
                    let seconds = timeOut % 60
                    self.shixiaoTimeL.text = "\(h):\(minutes):\(seconds)"
                }
                timeOut -= 1
            }
        }
        timer?.resume()
    }

\color{rgb(0 ,139, 139)}{OC 倒计时-GCD}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    __block NSInteger timeOut = 10000;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    //设置开始时间,三秒钟之后调用
    //dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW,3.0 *NSEC_PER_SEC);
    /*
     第一个参数:要给哪个定时器设置
     第二个参数:定时器的开始时间DISPATCH_TIME_NOW表示从当前开始
     第三个参数:定时器调用方法的间隔时间
     第四个参数:定时器的精准度,如果传0则表示采用最精准的方式计算,如果传大于0的数值,则表示该定时切换i可以接收该值范围内的误差,通常传0
     该参数的意义:可以适当的提高程序的性能
     注意点:GCD定时器中的时间以纳秒为单位(面试)
     */
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeOut <= 0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.shixiaoTimeL.text = @"00:00:00";
            });
        }else{
            long h = timeOut / 3600;
            long minutes = timeOut % 3600 / 60;
            long seconds = timeOut % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.shixiaoTimeL.text = [NSString stringWithFormat:@"%ld:%ld:%ld",h,minutes,seconds];
            });
            timeOut--;
        }
    });
    dispatch_resume(_timer);
    
    
    /* GCD定时器补充
     
     DISPATCH_SOURCE_TYPE_TIMER         定时响应(定时器事件)
     DISPATCH_SOURCE_TYPE_SIGNAL        接收到UNIX信号时响应
     
     DISPATCH_SOURCE_TYPE_READ          IO操作,如对文件的操作、socket操作的读响应
     DISPATCH_SOURCE_TYPE_WRITE         IO操作,如对文件的操作、socket操作的写响应
     DISPATCH_SOURCE_TYPE_VNODE         文件状态监听,文件被删除、移动、重命名
     DISPATCH_SOURCE_TYPE_PROC          进程监听,如进程的退出、创建一个或更多的子线程、进程收到UNIX信号
     
     下面两个都属于Mach相关事件响应
     DISPATCH_SOURCE_TYPE_MACH_SEND
     DISPATCH_SOURCE_TYPE_MACH_RECV
     下面两个都属于自定义的事件,并且也是有自己来触发
     DISPATCH_SOURCE_TYPE_DATA_ADD
     DISPATCH_SOURCE_TYPE_DATA_OR
     */
}

\color{rgb(0 ,139, 139)}{OC 倒计时-NSTimer}

/*
 说明:
 (1)runloop一启动就会选中一种模式,当选中了一种模式之后其它的模式就都不鸟。一个mode里面可以添加多个NSTimer,也就是说以后当创建NSTimer的时候,可以指定它是在什么模式下运行的。
 (2)它是基于时间的触发器,说直白点那就是时间到了我就触发一个事件,触发一个操作。基本上说的就是NSTimer
 */
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [NSThread detachNewThreadSelector:@selector(timer1) toTarget:self withObject:nil];
}
//创建定时器的第一种方法
-(void)timer1{
    NSLog(@"timer1_%@",[NSThread currentThread]);
    //1)创建定时器对象&2)默认把定时器添加到当前的runloop中,并且指定运行模式为默认
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];
    NSRunLoop *currentRunloop = [NSRunLoop currentRunLoop];//? 子线程对应runloop需要手动创建
    [currentRunloop run];//开启runloop
}
//创建定时器的第二种方法
-(void)timer2{
    NSLog(@"timer2_%@",[NSThread currentThread]);
    //1.获得定时器对象
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];
    //2.还需要添加到runloop
    //第一个参数:定时器对象
    //第二个参数:要设定的runloop的运行模式(只有当runloop在该运行模式下的时候timer才会工作)
    //默认运行模式
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    //界面跟踪(只有当runloop处于界面跟踪运行模式下定时器才会工作)
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
    //标记模式(并不是真正意义的运行模式  标记 == NSDefaultRunLoopMode + UITrackingRunLoopMode)
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)task{
    NSLog(@"task----%@--%@",[NSThread currentThread],[NSRunLoop currentRunLoop].currentMode);
}

timer1_<NSThread: 0x60000209d900>{number = 7, name = (null)}
task----<NSThread: 0x60000209d900>{number = 7, name = (null)}--kCFRunLoopDefaultMode
task----<NSThread: 0x60000209d900>{number = 7, name = (null)}--kCFRunLoopDefaultMode
task----<NSThread: 0x60000209d900>{number = 7, name = (null)}--kCFRunLoopDefaultMode
... ...



相关文章

  • 无标题文章

    iOS NSTimer使用详解-开启、关闭、移除 定时器定时器详解ios定时器关闭定时器NSTimer 1、要使用...

  • iOS进阶-谈谈定时器

    目录 iOS提供定时器API 定时器开发中的坑 一、 iOS提供定时器API 二、定时器开发中的坑 2.1、必须办...

  • 定时器

    定时器 兼容ios

  • iOS中的定时器

    点击这里>> cocoaChina: iOS中的定时器 iOS中定时器有三种,分别是NSTimer、CADispl...

  • GCD定时器使用

    iOS中的常用定时器分为这几类: NSTimer CADisplayLink GCD定时器 选择GCD定时器原因:...

  • iOS:NSTimer的几种创建方式

    在iOS开发中,经常会用到定时器,iOS中常用的定时器有三种:NSTimer,GCD,CADisplayLink。...

  • iOS Timer

    iOS开发中定时器经常会用到,iOS中常用的定时器有三种,分别是NSTime,CADisplayLink和GCD。...

  • 每日笔记

    1、通过safari打开网页 2、iOS的几种定时器及区别 iOS的几种定时器及区别 3、long long类型 ...

  • iOS三大定时器

    iOS开发中定时器经常会用到,iOS中常用的定时器有三种,分别是NSTime,CADisplayLink和GCD。...

  • 定时器的使用介绍

    iOS中的定时器大致分为这几类: NSTimer CADisplayLink GCD定时器 (一)NSTimer ...

网友评论

      本文标题:iOS 定时器

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