2013-04-29 124 views
2

嗨,我想與另一個線程啓動一個計時器,並希望在該線程中重複進程。我曾嘗試過,但不起作用。下面如何運行另一個線程並使用該線程運行計時器來重複進程?

[NSThread detachNewThreadSelector:@selector(setupTimerThread) toTarget:self withObject:nil]; 


    -(void)setupTimerThread 
    { 
    NSLog(@"inside setup timer thread"); 
    // self.startTiemr = [[NSTimer alloc]init]; 
    startTiemr = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(triggerTimer) userInfo:nil repeats:YES]; 

    runLoop = [NSRunLoop currentRunLoop]; 
    [runLoop addTimer:startTiemr forMode:NSRunLoopCommonModes]; 
     [runLoop run];  
} 

我的代碼片段給出任何人都可以建議我一個適當的方式做到這一點?

在此先感謝。

+0

看看下面的鏈接 http://stackoverflow.com/questions/7055424/ios-start-background-thread – Pradeep 2013-04-29 10:30:27

+0

感謝您的關注,但我要開始運行一個定時器,定時器線程將在30秒後重復 – jpd 2013-04-29 10:40:26

回答

2
#import "TimePassViewController.h" 

@interface TimePassViewController() 

@end 

@implementation TimePassViewController 
{ 
    NSTimer *timer; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // [self performSelectorOnMainThread:@selector(yourmethod) withObject:nil waitUntilDone:NO]; 


    NSThread* myThread = [[NSThread alloc] initWithTarget:self 
               selector:@selector(yourmethod) 
                object:nil]; 
    [myThread start]; // Actually create the thread 

} 





-(void)yourmethod 
{ 
    @autoreleasepool 
    { 
     NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop]; 
     timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES]; 
     [TimerRunLoop run]; 
    } 
    //timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES]; 
} 

-(void)timerMethod 
{ 
    NSLog(@"aaaaaaaaaaaa"); 
    //[timer invalidate]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 
+0

謝謝你的答案,但我想在一個單獨的線程上運行它不在主線程 – jpd 2013-04-29 11:16:34

+0

看看編輯答案 – Pradeep 2013-04-29 11:29:14

+0

我在哪裏可以找到它? – jpd 2013-04-29 14:03:47

2

嘗試此代碼:

NStimer *uptimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(bachground_todaylist) userInfo:nil repeats:YES]; 

-(void)bachground_todaylist 
    { 

     [self performSelectorInBackground:@selector(yourmethod) withObject:nil]; 


    } 
you wants to stop proces 

[uptimer無效];

+0

performselectorinbackground將在所有(yourmethod)完成後停止? – jpd 2013-04-29 10:58:10

+0

如果你想停止然後設置定時器重複NO – 2013-04-29 10:59:52

+0

,不僅如此,而且如果它在每1秒後重復每次創建新線程 – jpd 2013-04-30 05:12:51

相關問題