我正在尝试创建一个在不同线程中执行子方法的控制方法。我已经研究过NSTimer,但是有几个子方法没有在确切的时间间隔内执行。
以下是5个区间:
间隔1 - 3应该很容易使用NSTimer。有关实施其他技巧的提示吗?
提前致谢!
答案 0 :(得分:1)
对于(4)和(5),如果dispatch_walltime
不够准确,您需要NSTimer
。
/* timespec for midnight, new years day 2014 */
struct tm time = {
.tm_sec = 0,
.tm_min = 0,
.tm_hour = 0,
.tm_mday = 1,
.tm_mon = 1,
.tm_year = 2014,
.tm_wday = -1, // I think -1 is wildcard here, can someone help?
.tm_yday = -1,
.tm_isdst = TRUE
};
const struct timespec whenToFire = {
.tv_sec = mktime(time),
.tv_nsec = 0
};
dispatch_time_t time = dispatch_walltime(&whenToFire,0);
/* a lower-priority queue may delay firing */
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT);
dispatch_source_t timeSrc = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
0, 0, queue);
dispatch_source_set_timer(timeSrc, time, 100000 , 100);
dispatch_source_set_event_handler(timeSrc, ^{
/* only run once */
static dispatch_once_t token;
dispatch_once(&token, ^{
/* code to run on New Years Day here */
dispatch_source_cancel(timeSrc);
});
});