[英]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_create
與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
第四個參數)。
要取消此計時器,請使用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);
});
尋找更多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.