如何运行另一个线程并使用该线程运行计时器来重复进程?

问题描述:

嗨,我想与另一个线程启动一个计时器,并希望在该线程中重复进程。我曾尝试过,但不起作用。下面如何运行另一个线程并使用该线程运行计时器来重复进程?

[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://*.com/questions/7055424/ios-start-background-thread – Pradeep 2013-04-29 10:30:27

+0

感谢您的关注,但我要开始运行一个定时器,定时器线程将在30秒后重复 – jpd 2013-04-29 10:40:26

#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

尝试此代码:

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