Search code examples
iosobjective-cnstimer

execute task with a time sequence in iOS


I want to execute some codes with a time sequence like [5s, 10s, 10s, 20s], which means that it executes the code after 5 seconds, and executes it the second time after 10s. I want to use NSTimer, but I can not figure out how can I do.


Solution

  • My method is a bit simpler to implement.

    - (void)startExecute
      { 
        intervals=@[@(5),@(10),@(10),@(20)]; // class member
        isExecuting=YES; // class member
        [self executeTaskAtIndex:0]; // start first task
      }
    
    - (void)executeTaskAtIndex:(NSUInteger)index
      { 
       if (index>=intervals.count || !isExecuting) // no intervals left or reset execution
           return;
       NSNumber *intervalNumber=intervals[index];
       NSTimeInterval interval=intervalNumber.doubleValue;
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          if(!isExecuting)
             return;
          // execute your task here
          //...
          index++;
          [self executeTaskAtIndex:index]; // another iteration
       });
      }