3

I would like to use an NSOperationQueue which has got a timer inside it. For example - I download 1 element (complete the 1st NSOperation) then I want to wait for 3 seconds before the compiler goes on to the next operation. After the 2nd NSOperation has been completed I want it to wait for the same 3 seconds and then start the operation number 3.

How can this behaviour be implemented? I have no prior experience of using NSTimer or NSRunLoop and I'm unsure whether I should use them at all.

Thanks in advance.

tkanzakic
  • 5,499
  • 16
  • 34
  • 41
Sergey Grischyov
  • 11,995
  • 20
  • 81
  • 120

3 Answers3

4

As long as the operations are executed in background thread;

You can set the maxConcurrentOperationCount to 1 and use the sleep(3) for 3 seconds in your operation block.

Mert
  • 6,025
  • 3
  • 21
  • 33
1

Use sleep(int secondsToSleep);

Devfly
  • 2,495
  • 5
  • 38
  • 56
0

Using sleep and maxConcurrentOperationCount is all you need if you just want to wait for 3 seconds after your operation does something.

If you need something more complex you could use timeIntervalSinceDate in a while loop. This is useful if your operation does some processing that can take an indeterminate time (in my case I need to run a remote create account process) and you want to wait at least, or at most, X seconds before running the next operation in the queue. You can make subsequent NSOperations dependent on completion of a previous operation.

Use addDependency to sequence NSOperation to wait until previous operation completed :

NSOperationQueue *ftfQueue = [NSOperationQueue new];
// Does this user have an account?
// createFTFAccount is subclass of NSOperation.  
FTFCreateAccount *createFTFAccount = [[FTFCreateAccount alloc]init];
[createFTFAccount setUserid:@"a-user-id"];
[ftfQueue addOperation:createFTFAccount];
// postFTFRoute subclass NSOperation    
FTFPostRoute *postFTFRoute = [[FTFPostRoute alloc]init];
// Add postFTFRoute with a dependency on Account Creation having finished 
[postFTFRoute addDependency:createFTFAccount];
[ftfQueue addOperation:postFTFRoute];

In the NSOperation subclass main check if the operation has finished or if its taking too long

#import <Foundation/Foundation.h>
@interface FTFCreateAccount : NSOperation
    @property (strong,nonatomic) NSString *userid;
@end    



@implementation FTFCreateAccount
{
    NSString *_accountCreationStatus;
}

- (void)main {

    NSDate *startDate = [[NSDate alloc] init];
    float timeElapsed;
    ..... 
    .....
    .....

    // Hold it here until a reply comes back from the account creation process 
    // Or the process is taking too long
    while ((!_accountCreationStatus) && (timeElapsed < 3.0)) {
        NSDate *currentDate = [[NSDate alloc] init];            
        timeElapsed = [currentDate timeIntervalSinceDate:startDate];
    }
    // Code here to do something dependent on _accountCreationStatus value

}
Peter Todd
  • 8,561
  • 3
  • 32
  • 38