下面有兩種做法
1.使用日期組件 NSDateComponents
2.使用NSString 生成一個日期
// 創建一個日歷對象
NSCalendar *calendar = [NSCalendar currentCalendar];
// 創建日期組件
NSDateComponents *dc = [[NSDateComponents alloc]init];
// 設置當前時間
[dc setCalendar: calendar];
[dc setYear: 2014];
[dc setMonth: 4];
[dc setDay: 9];
[dc setHour:21];
[dc setMinute:26];
[dc setSecond:0];
NSString *dateStr = @"2014-04-0921:38:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat=@"yyyy-MM-ddHH:mm:ss";
NSDate *schuduleNate = [dc date];
NSDate *schuduleNate2 = [formatter dateFromString:dateStr];
NSDate *dateNow = [NSDate date];
// 計算時間差
NSTimeInterval num = [schuduleNate2 timeIntervalSinceDate:dateNow];
NSLog(@"%f 後開始執行任務",num);
// 任務池
NSRunLoop *mainLoop = [NSRunLoop currentRunLoop];
//
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:num target:self selector:@selector(scheduleTask) userInfo:nil repeats:NO];
NSTimer *timer2 = [NSTimer scheduledTimerWithTimeInterval:num+3 target:self selector:@selector(scheduleTask) userInfo:nil repeats:NO];
// 添加到任務池中
[mainLoop addTimer:timer forMode:NSDefaultRunLoopMode];
[mainLoop addTimer:timer2 forMode:NSDefaultRunLoopMode];
[mainLoop run];
輸出信息
2014-04-09 21:37:54.289 WeChat[1810:60b] 5.710526後開始執行任務
2014-04-09 21:38:00.001 WeChat[1810:60b] do some thing
2014-04-09 21:38:03.001 WeChat[1810:60b] do some thing