Strange behavior of dispatch_after ()

I am writing an application that will perform several tasks at once. One of the tasks is to complete the task every 200 ms . For this, I use two methods that call each other. The first method simply calls the second, and the second method calls the first with a delay using dispatch_after ().

After several iterations (300-400 times), the block in dispatch_after is not executed after 200 ms. It takes ~ 5-10 seconds before the block is executed . Please let me know the reason for the behavior (delay). I also tried NSThread (sleepForTimeInterval :), and I am facing the same problem too. I am stuck. Please help me.

The code is below.

screen.h

#import <Foundation/Foundation.h>

@interface Screen : NSObject

-(void) firstMethod;
-(void) secondMethod;
@end

Screen.m

#import "Screen.h"

@implementation Screen

int i=0;
dispatch_queue_t another_queue;
dispatch_time_t pop_time;

-(Screen*) init {
    self = [super init];
    if (self) {
        another_queue = dispatch_queue_create("com.test.timer.2", NULL);
    }
    return self;
}

-(void) firstMethod {
    i++;
    NSLog(@"i value : %d",i);
    [self secondMethod];
}

-(void) secondMethod {
    pop_time = dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC);
    dispatch_after(pop_time, another_queue, ^(void){
        [self firstMethod];
    });
}

@end

Appdelegate.h

#import <Cocoa/Cocoa.h>
#import "Screen.h"

@interface AppDelegate : NSObject <NSApplicationDelegate>

@property (assign) IBOutlet NSWindow *window;

@end

AppDelegate.m

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    Screen* screen = [[Screen alloc] init];
    dispatch_queue_t first_queue = dispatch_queue_create("com.test.timer", NULL);
    dispatch_block_t blk =^(void) {
        [screen firstMethod];
    };
    dispatch_async(first_queue, blk);
}

@end
+4
3

, ? , , App Nap . , , .

+6

" " "App Nap".

: : , dispatch_after 10% iOS?.

, NSTimer, lib, . . : Gist: RXTimer

Edit:

Mac OS X App Nap , , , "".

+1

OS X. 1000% .

Nap :

defaults write NSGlobalDomain NSAppSleepDisabled -bool YES
-1

Source: https://habr.com/ru/post/1529940/


All Articles