GCD全解-03-dispatch_after/dispatch_time-延迟调度和操作

GCD系列是阅读官方文件和在实践中总结的一些常见的GCD用法,基本涉及全部的GCD内容形成的集合文章,文章重点在与精简和全面覆盖。

学习本集合你可以了解:
1. GCD是如何做到多线程调度的
2. 对比其他iOS的多线程方案,GCD的优势和劣势
3. 如何使用GCD相关的API

我将在后续不断补充详细内容和实际案例, 欢迎关注,提问和讨论

01-dispatch-iOS系统调度

02-dispatch_queue-调度队列

03-dispatch_after/dispatch_time-延迟调度和操作

04-dispatch_barrier_sync/async-线程阻塞

05-dispatch_apply-重复提交操作

06-dispatch_once-单次执行

07-dispatch_semaphore-信号量/数据同步

08-dispatch_group-调度组/多异步操作控制

09-dispatch_block-GCD取消操作

10-dispatch_source-调度资源

11-GCD死锁

dispatch_after

延时操作的API,通常Queue会在主线程,但是也可以自定义线程

* @functoin Schedule a block for execution on a given queue at a specified time.
 * @param when
 * A temporal milestone returned by dispatch_time() or dispatch_walltime().

void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block);
* @param context
 * The application-defined context parameter to pass to the function.
 *
 * @param work
 * The application-defined function to invoke on the target queue. The first
 * parameter passed to this function is the context provided to
 * dispatch_after_f().
 * The result of passing NULL in this parameter is undefined.

void dispatch_after_f(dispatch_time_t when, dispatch_queue_t queue, void *_Nullable context,    dispatch_function_t work);

dispatch_time

A somewhat abstract representation of time; 
where zero means "now" and DISPATCH_TIME_FOREVER means "infinity" and every value in between is an opaque encoding.
typedef uint64_t dispatch_time_t;

#define DISPATCH_TIME_NOW (0ull)
#define DISPATCH_TIME_FOREVER (~0ull)

// Create dispatch_time_t relative to the default clock or modify an existing dispatch_time_t.
//An optional dispatch_time_t to add nanoseconds to. If zero is passed, then dispatch_time() will use the result of mach_absolute_time().
dispatch_time_t dispatch_time(dispatch_time_t when, int64_t delta);

常见用法

dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
                                 (int64_t)(60 * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
    # 主线程执行代码
});

NSLog(@"你好吗?");

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_queue_create("ll", NULL), ^{
       NSLog(@"你好");
});

这里都是一样的,只不过调用的线程种类不一样
2016-11-05 17:10:43.921 Multithreading[16258:488248] 你好吗?
2016-11-05 17:10:47.217 Multithreading[16258:488289] 你好
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值