NSTimer可以在APP中设置定时执行的任务. 而使用setKeepAliveTimeout: handler:可以设置APP后台运行时的定时任务.
NSTimer
下边是NSTimer的头文件, 其中介绍了timerWithTimeInterval, scheduledTimerWithTimeInterval, initWithFireDate, fire, invalidate等方法.
使用fire方法可以立即触发定时器:
1. 在重复执行的定时任务中使用fire可以立即触发任务, 但不会中断其之前的定时计划.
2. 在一次性的定时任务中使用fire立即触发任务, 但该定时器立即失效.
invalidate方法是唯一一个可以将定时器从runloop中移除的方法.
/* NSTimer.h
Copyright (c) 1994-2014, Apple Inc. All rights reserved.
*/
#import <Foundation/NSObject.h>
#import <Foundation/NSDate.h>
@interface NSTimer : NSObject
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep NS_DESIGNATED_INITIALIZER;
- (void)fire;
@property (copy) NSDate *fireDate;
@property (readonly) NSTimeInterval timeInterval;
// Setting a tolerance for a timer allows it to fire later than the scheduled fire date, improving the