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

时间:2013-04-29 10:24:09

标签: iphone nstimer nsthread

嗨我想用另一个线程启动一个计时器,并希望在该线程中重复进程。我曾经尝试但是没有用。

我的代码段在下面给出

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

任何人都可以建议我这样做吗?

提前致谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

试试这段代码:

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