iPhone - a delay between operations in the queue

后端 未结 4 1867
挽巷
挽巷 2021-02-03 15:20

I am adding operations to the queue using something like this

NSInvocationOperation *operation0 = [[NSInvocationOperation alloc] 
initWithTarget:self
selector:@s         


        
4条回答
  •  爱一瞬间的悲伤
    2021-02-03 15:43

    Using sleep is a big waste of a thread. This is bad in the Ghostbusters' sense.

    If you need a queue that executes its operations non-concurrently i.e. sequentially you can simpy set its maxConcurrentOperationCount variable to 1.

    queue.maxConcurrentOperationCount = 1;
    

    To pause between operations you could do two different things:

    a) Delay the queueing of each operation:

    //loop over the operations to be queued with and index
          double delayInSeconds = 2.0 * index;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                queue.addOperation(operation at index); 
            });
    

    This will queue all operations without blocking.

    b) Every operation has to implement

    - (BOOL)isFinished
    

    as you probably already know.

    If your operation is "done" just delay setting its "done" variable by your desired delay. Use something like:

    // Operation is done with its work, but we tell the Queue only after 2 seconds, so the queue will start the next operation later
    double delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
     __weak __typeof(self)weakSelf = self;
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [weakSelf willChangeValueForKey:@"isExecuting"];
        [weakSelf willChangeValueForKey:@"isFinished"];
        weakSelf.executing = NO;
        weakSelf.finished  = YES;
        [weakSelf didChangeValueForKey:@"isFinished"];
        [weakSelf didChangeValueForKey:@"isExecuting"];
        });
    

    Variant a) guarantees a pause between starting times of operations. Variant b) guarantees a pause between the end of an operation and the start of a next operation.

提交回复
热议问题