我在與NSThread一個問題,我不很瞭解..火一個NSThread每一個 'X' secondes
如何以及創建一個NSThread:
- (ID)initWithTarget (ID),目標選擇:(SEL)選擇對象:(ID)的說法 然後...
我是用NSThread和他所有的方法有點迷惑。
我想創建一個NSThread和消防它的每一個5分鐘(當然繼續使用我的應用程序,而潛伏期:)
你能幫助我嗎?
danke!
我在與NSThread一個問題,我不很瞭解..火一個NSThread每一個 'X' secondes
如何以及創建一個NSThread:
我是用NSThread和他所有的方法有點迷惑。
我想創建一個NSThread和消防它的每一個5分鐘(當然繼續使用我的應用程序,而潛伏期:)
你能幫助我嗎?
danke!
或者使用GCD的調度源,因爲Apple建議從NSThread
遷移使用。
假設下面的ivar存在:
dispatch_source_t _timer;
然後,例如:
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, backgroundQueue);
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC, 0.05 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
NSLog(@"periodic task");
});
dispatch_resume(_timer);
這將觸發一個小的任務上的背景隊列每2秒用小余地。
您可以設置一個NSTimer了將運行啓動你的線程
// Put in a method somewhere that i will get called and set up.
[NSTimer timerWithTimeInterval:10 target:self selector:@selector(myThreadMethod) userInfo:nil repeats:YES];
或
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(myThreadMethod) userInfo:nil repeats:YES];
您還可以將其設置爲一個NSTimer的方法,所以你可以設置的poroperties定時器。如開始和結束。
- (void)myThreadMethod
{
[NSThread detachNewThreadSelector:@selector(someMethod) toTarget:self withObject:nil];
}
我建議的NSTimer + NSThred你的目的
[NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(triggerTimer:)
userInfo:nil repeats:YES];
-(void) triggerTimer:(NSTimer *)theTimer
{
//Here perform the thread operations
[NSThread detachNewThreadSelector:@selector(myThreadMethod) toTarget:self withObject:nil];
}
您可以嘗試使用的NSTimer來實現它。在你的主線程註冊的NSTimer:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
,你可以有-doSomething啓動一個線程做你的實際工作:
-(void) doSomething {
dispatch_queue_t doThings = dispatch_queue_create("doThings", NULL);
dispatch_async(doThings, ^{
//Do heavy work here...
dispatch_async(dispatch_get_main_queue(), ^{
//Here is main thread. You may want to do UI affair or invalidate the timer here.
});
});
}
您可以參考NSTimer Class和GCD獲取更多信息。
喲謝謝你的答案,我只需要改變數字2來激發我的方法? – xGoPox
我這麼認爲。它應該是重複性任務的一個非常輕量級的解決方案。它利用塊的優勢使其成爲有吸引力的內聯解決方案。 – FluffulousChimp