Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

ios - method not called with dispatch_async and repeating NSTimer

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 ");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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).

To cancel this timer, use dispatch_source_cancel:

dispatch_source_cancel(timer);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...