How can I delay execution of a block that has been queued to dispatch_after?

Let's say I want to execute a block of code later, so I call dispatch_after

like this:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    /* code */
});

      

But what if I want to "pause" my program before the execution has even begun? Let's say I want to pause a program for 1 second after this call for an unknown amount of time. Then, after a pause, I would like to resume the 2 second wait in the queue. So it looks something like this:

  • dispatch_after call with a delay of 2 seconds
  • after 1 second, pause the program for an unknown time
  • after resuming, wait 1 second and execute the block (so the total delay is 2 seconds).

Is there a way to do this? Or should I use a different approach?

I know there are dispatch_suspend

and dispatch_resume

, but they don't really work for me (or I just don't know how to use them correctly).

The solution does not have to include a block, it can also be a delayed callback to the specified function. The point is, I want to be able to pause the timeout until it is executed.

+3


source to share


2 answers


You cannot achieve this, but there is a way to do this.

Delay your method 2 seconds:

[self performSelector:@selector(yourMethod) withObject:nil afterDelay:2.0];

After 1 second, cancel your method:



[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(yourMethod) object:nil];

After unknown time, remember your method and delay to execute it after 1 second:

[self performSelector:@selector(yourMethod) withObject:nil afterDelay:1.0];

+1


source


Put your block in a method

-(void)myMethod{
//implementation of the block
}

      

where you want to call the BUT block, delay 2 seconds before it,



call

[self performSelector:@selector(myMethod) withObject:nil afterDelay:2.0];

      

Hope it helps

0


source







All Articles