原型:dispatch_time(<#dispatch_time_t when#>, <#int64_t delta#>)
第一个参数:是从什么时间开始,一般直接传 DISPATCH_TIME_NOW; 表示从现在开始
第二个参数:表示延迟多久,具体的时间长度(int64_t类型 ), 可以写成这种形式 (int64_t)3* NSEC_PER_SEC
返回值:返回给定时间延迟delta纳秒对应的时间,delta单位是纳秒
#define NSEC_PER_SEC 1000000000ull // 定义一秒=10亿纳秒
#define USEC_PER_SEC 1000000ull // 定义一秒=100万微妙
#define NSEC_PER_USEC 1000ull // 定义一微妙=100纳秒
时间换算单位
1s(秒second)= 1000ms(毫秒millisecond)= 1000 000μs(微妙microsecond) = 1000 000 000ns(纳秒nanosecond)
1秒的写作方式可以是 1* NSEC_PER_SEC; 1000* NSEC_PER_MSEC
或 USEC_PER_SEC* NSEC_PER_USEC
dispcth_after 是将block 中的任务延迟添加到它将要执行的队列中去,而并不一定添加到队列中就立即会去执行任务。如果主队列中还有另外的任务假设A、B 要执行,那么这个任务会在任务A、B 执行完后才会开始执行。
下面代码表示是在5秒中后将任务添加到主队列中,验证的代码如下:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 *
NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
NSLog(@"我是延迟执行的函数 --- ");
});
dispatch_queue_t delayQueue = dispatch_queue_create("rx.queue.delay", nil);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)),
delayQueue, ^{
NSLog(@"我是在子线程 delayQueue 中延迟执行的函数 --- ");
});
NSLog(@"开始执行好耗时操作 --- ");
for (int i = 0; i<1000000000; i++) {
self.testCount ++;
}
NSLog(@"耗时操作执行完成 --- ");
NSLog(@"第二个开始执行好耗时操作 --- ");
for (int i = 0; i<1000000000; i++) {
self.testCount ++;
}
NSLog(@"第二个耗时操作执行完成 --- ");