如何运行另一个线程并使用该线程运行计时器来重复进程?
问题描述:
嗨,我想与另一个线程启动一个计时器,并希望在该线程中重复进程。我曾尝试过,但不起作用。下面如何运行另一个线程并使用该线程运行计时器来重复进程?
[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];
}
我的代码片段给出任何人都可以建议我一个适当的方式做到这一点?
在此先感谢。
答
#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
答
尝试此代码:
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无效];
看看下面的链接 http://stackoverflow.com/questions/7055424/ios-start-background-thread – Pradeep 2013-04-29 10:30:27
感谢您的关注,但我要开始运行一个定时器,定时器线程将在30秒后重复 – jpd 2013-04-29 10:40:26