方法一:
-(void) viewDidLoad{
[self performSelectorInBackground:@selector(call1) withObject:nil];
}
-(void) call1{
timer1 = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(doSomething) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSRunLoopCommonModes];
}
-(void) call2{
// do something
timer1 invalidate];
timer1 = nil;
}
方法二:
- (void)viewDidAppear:(BOOL)animated {
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) object:nil];
[timerThread start];
}
-(void)timerStart
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];//一定要retain,不然timerStart执行完后,NSTimer就被释放了。
[runLoop run];
[pool release];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[timer invalidate];
}
方法三:
timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(SendHeartBeat) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:heartTimer forMode:NSDefaultRunLoopMode];
如果想要在后台继续执行timer的话实现:
- (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. if ([[UIDevice currentDevice] isMultitaskingSupported]) { self.backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^{ }]; } } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. if ([[UIDevice currentDevice] isMultitaskingSupported]) { [application endBackgroundTask:self.backgroundTaskIdentifier]; } }