在子线程中使用定时器,将定时器添加到RunLoop中

参考自:http://my.oschina.net/u/936286/blog/159490


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    dispatch_queue_t queue = dispatch_queue_create("kk", DISPATCH_QUEUE_SERIAL);
    
    // 串行队列中执行异步任务
    dispatch_async(queue, ^{
        
        // 在子线程中使用定时器
        
        /*************************************************************/
        
        /*
        
        // 第一种方式
         
        // 此种方式创建的timer已经添加至runloop中
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(doSomething) userInfo:nil repeats:NO];
        
        // 在线程中使用定时器,如果不启动run loop,timer的事件是不会响应的,而子线程中runloop默认没有启动
        // 让线程执行一个周期性的任务,如果不启动run loop, 线程跑完就可能被系统释放了
        [[NSRunLoop currentRunLoop] run];// 如果没有这句,doSomething将不会执行!!!
         
        */
        
        /*************************************************************/
        
        
        
        /*************************************************************/
        
        // 第二种方式
        NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(doAnything) userInfo:nil repeats:NO];
        
        // 将定时器添加到runloop中
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        
        // 在线程中使用定时器,如果不启动run loop,timer的事件是不会响应的,而子线程中runloop默认没有启动
        // 让线程执行一个周期性的任务,如果不启动run loop, 线程跑完就可能被系统释放了
        [[NSRunLoop currentRunLoop] run];// 如果没有这句,doAnything将不会执行!!!
        
        /*************************************************************/
        
        NSLog(@"子线程结束");
        
    });
}

- (void)doSomething{

    NSLog(@"doSomething...");
}

- (void)doAnything{
    
    NSLog(@"doAnything...");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值