繁体   English   中英

没有使用dispatch_async调用并重复NSTimer的方法

[英]method not called with dispatch_async and repeating NSTimer

我正在开发一个应用程序,我想使用dispatch_async在单独的队列中调用方法。 我希望在一定的时间间隔后重复调用该方法。 但是方法没有被调用。

我不知道什么是错的。 这是我的代码:

dispatch_async( NotificationQueue, ^{

        NSLog(@"inside queue");
        timer = [NSTimer scheduledTimerWithTimeInterval: 20.0
                                                 target: self
                                               selector: @selector(gettingNotification)
                                               userInfo: nil
                                                repeats: YES];

        dispatch_async( dispatch_get_main_queue(), ^{
            // Add code here to update the UI/send notifications based on the
            // results of the background processing

        });
    });

-(void)gettingNotification {
    NSLog(@"calling method ");
}

如果要在dispatch_queue_t上调用重复计时器,请将dispatch_source_createDISPATCH_SOURCE_TYPE_TIMER一起使用:

dispatch_queue_t  queue = dispatch_queue_create("com.firm.app.timer", 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 20ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC);

dispatch_source_set_event_handler(timer, ^{

    // stuff performed on background queue goes here

    NSLog(@"done on custom background queue");

    // if you need to also do any UI updates, synchronize model updates,
    // or the like, dispatch that back to the main queue:

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"done on main queue");
    });
});

dispatch_resume(timer);

这创建了一个每20秒运行一次的计时器( dispatch_source_set_timer第三个参数),具有一秒的余地( dispatch_source_set_timer第四个参数)。

要取消此计时器,请使用dispatch_source_cancel

dispatch_source_cancel(timer);

试试这个代码

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    dispatch_async( dispatch_get_main_queue(), ^{

        timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
                                               selector: @selector(gettingNotification) userInfo: nil repeats: YES];
        // Add code here to update the UI/send notifications based on the
        // results of the background processing

    });
});

-(void)gettingNotification {

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         //background task here
    dispatch_async( dispatch_get_main_queue(), ^{
        // update UI here
        );
});
}
int parameter1 = 12;
float parameter2 = 144.1;

// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
    NSLog(@"parameter1: %d parameter2: %f", parameter1, parameter2);
});

寻找更多

如何在延迟后触发一个块,比如-performSelector:withObject:afterDelay:?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM