下面有两种做法
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];
[email protected]"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
IOS OC 多任务定时器 NSRunLoop 管理 NSTimer