在 iOS 中,如果希望應用程式在指定時間執行某個任務,可以利用 NSDateComponents 或 NSDateFormatter 建立目標時間,再透過 NSTimer 與 NSRunLoop 安排執行。以下整理兩種常見做法。
NSDateComponents 適合直接指定年、月、日、時、分、秒等欄位,程式碼語意清楚,很適合用來建立一個明確的排程時間。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setCalendar:calendar];
[components setYear:2014];
[components setMonth:4];
[components setDay:9];
[components setHour:21];
[components setMinute:26];
[components setSecond:0];
NSDate *scheduleDate = [components date];
如果日期來源是字串,例如從伺服器或設定檔讀取,可以使用 NSDateFormatter 解析成 NSDate。
NSString *dateString = @"2014-04-09 21:38:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *scheduleDate = [formatter dateFromString:dateString];
取得目標時間後,可以計算與現在時間的差值,再把 NSTimer 加入 RunLoop。若需要多個任務,也可以建立多個 Timer,並分別加入 mainRunLoop。
NSDate *now = [NSDate date];
NSTimeInterval interval = [scheduleDate timeIntervalSinceDate:now];
NSRunLoop *mainLoop = [NSRunLoop currentRunLoop];
NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(scheduleTask)
userInfo:nil
repeats:NO];
NSTimer *timer2 = [NSTimer scheduledTimerWithTimeInterval:interval + 3
target:self
selector:@selector(scheduleTask)
userInfo:nil
repeats:NO];
[mainLoop addTimer:timer1 forMode:NSDefaultRunLoopMode];
[mainLoop addTimer:timer2 forMode:NSDefaultRunLoopMode];
執行後,可以看到類似以下的輸出:
5.710526 後開始執行任務
do some thing
do some thing
這種做法的核心概念是:NSTimer 必須依附在 RunLoop 上才能穩定觸發,而 NSRunLoop 則負責管理事件來源與定時器。