没有使用dispatch_async调用并重复NSTimer的方法 [英] method not called with dispatch_async and repeating NSTimer
问题描述
我正在开发一个应用程序,我希望使用 dispatch_async
在单独的队列中调用方法。我希望在一定的时间间隔后重复调用该方法。但是这个方法没有被调用。
I am developing an app where i want to call method in separate queue using dispatch_async
. I want to call that method repeatedly after certain interval of time. But the method is not getting called.
我不知道什么是错的。这是我的代码:
I don't know whats wrong. Here is my code:
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_create
,带有DISPATCH_SOURCE_TYPE_TIMER
:
If you want a repeating timer to be invoked on a dispatch_queue_t
, use dispatch_source_create
with a DISPATCH_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
)。
That creates a timer that runs once every 20 seconds (3rd parameter to dispatch_source_set_timer
), with a leeway of a one second (4th parameter to dispatch_source_set_timer
).
要取消此计时器,请使用 dispatch_source_cancel
:
To cancel this timer, use dispatch_source_cancel
:
dispatch_source_cancel(timer);
这篇关于没有使用dispatch_async调用并重复NSTimer的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!