Check if NSTimer selector has finished working

2019-08-14 05:19发布

问题:

I am calling a service method in NSTimer after every 3 seconds. However before each time that method is being called, I want to check if previous one in timer is complete or not. I have done following which is not resulting in success.

timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(CallParseOperation) userInfo:nil repeats:YES]; 

CheckOperation:

-(void)CheckOperation{

    if([Data getInstance].kOperation == TRUE)
    {
        [self CallParseOperation];
    }

}

CallParseOperation:

-(void)CallParseOperation{


    [Data getInstance].kOperation = FALSE;
    operationQueue=[[NSOperationQueue alloc] init];
    ParseOperation *obj=[[ParseOperation alloc] initWithMembers:ID];
    NSInvocationOperation *reloadOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(tableReload) object:nil];
    [reloadOp addDependency:obj];
    [operationQueue addOperation:obj];
    [operationQueue addOperation:reloadOp];
    //[operationQueue waitUntilAllOperationsAreFinished];
    [obj release];
    [reloadOp release];

} 

Somewhere at the end of this implementation I am setting this bool as TRUE. But this is not working. The control is just stuck inside this timer.

回答1:

You should set the kOperation to FALSE before you call the method CallParseOperation otherwise it will always be true and will run everytime.

Instead of setting your timer to repeat, set it to fire once and then set it off again at the end of your parsing. That way it will run every x seconds AFTER processing rather than every x seconds regardless of whether it has finished the previous process or not.