2012-12-13 30 views
3

我想使用一個NSOperationQueue其中有一個計時器。 例如 - 我下載了1個元素(完成第一個NSOperation),然後我想在之前等待3秒編譯器進入下一個操作。第二個NSOperation已完成後,我希望它等待相同的3秒,然後開始操作編號3.NSOperationQueue帶計時器

此行爲如何實現?我以前沒有使用NSTimerNSRunLoop的經驗,我不確定是否應該使用它們。

在此先感謝。

回答

4

只要操作在後臺線程中執行;

您可以將maxConcurrentOperationCount設置爲1,並在您的操作塊中使用睡眠(3)3秒鐘。

2

使用sleep(int secondsToSleep);

0

如果您只是想在操作執行某些操作後等待3秒鐘,則只需使用sleep和maxConcurrentOperationCount即可。

如果您需要更復雜的東西,可以在while循環中使用timeIntervalSinceDate。如果您的操作執行了一些可能需要不確定時間的處理(在我的情況下,我需要運行遠程創建帳戶進程)並且您希望至少等待或至多等待X秒,然後再運行下一個操作隊列。您可以使後續的NSOperations依賴於先前操作的完成。

使用addDependency測序的NSOperation等到前面的操作完成:

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]; 

在子類的NSOperation主要檢查操作是否已完成,或者如果它的時間太長

#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 

}