dispatch_after equivalent in NSOperationQueue

拜拜、爱过 提交于 2019-12-03 23:19:01

NSOperationQueue doesn't have any timing mechanism in it. If you need to set up a delay like this and then execute an operation, you'll want to schedule the NSOperation from the dispatch_after in order to handle both the delay and making the final code an NSOperation.

NSOperation is designed to handle more-or-less batch operations. The use case is slightly different from GCD, and in fact uses GCD on platforms with GCD.

If the problem you are trying to solve is to get a cancelable timer notification, I'd suggest using NSTimer and invalidating it if you need to cancel it. Then, in response to the timer, you can execute your code, or use a dispatch queue or NSOperationQueue.

You can keep using dispatch_after() with a global queue, then schedule the operation on your operation queue. Blocks passed to dispatch_after() don't execute after the specified time, they are simply scheduled after that time.

Something like:

dispatch_after
(
    mainPopTime,
    dispatch_get_main_queue(),
    ^ {
        [myOperationQueue addOperation:theOperationObject];
    }
);

You could make an NSOperation that performs a sleep: MYDelayOperation. Then add it as a dependency for your real work operation.

@interface MYDelayOperation : NSOperation
...
- (void)main
{
    [NSThread sleepForTimeInterval:delay]; // delay is passed in constructor
}

Usage:

NSOperation *theOperationObject = ...
MYDelayOperation *delayOp = [[MYDelayOperation alloc] initWithDelay:5];
[theOperationObject addDependency:delayOp];
[myOperationQueue addOperations:@[ delayOp, theOperationObject] waitUntilFinished:NO];
[operationQueue performSelector:@selector(addOperation:) 
                     withObject:operation 
                     afterDelay:delay];

Swift 4:

DispatchQueue.global().asyncAfter(deadline: .now() + 10 { [weak self] in
                guard let `self` = self else {return}

                self. myOperationQueue.addOperation {
                    //...code...
                }
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!