我对Timer.scheduledTimer()
如果执行比指定的withTimeInterval:
需要更多时间触发代码块有疑问。Swift`Timer`在指定的时间间隔之前触发
在执行完程序段或执行程序段的第一条语句后,是否开始倒计时?
//Logic is to waste the time in the block which will take more than 5 secs to run.
Timer.scheduledTimer(withTimeInterval: 5, repeats: true){
timer in
var sum = 0
var count = 0
print("START===================================")
print(Int64(Date().timeIntervalSince1970 * 1000))
for i in 2..<100000
{
for j in 2..<10000
{
sum = i+j
}
}
print(sum) // Ignore this. sum is used here so that compiler might won't be able to remove the loop in the optimisations due to unused variable reason.
print(Int64(Date().timeIntervalSince1970 * 1000))
print("END===================================")
}
RunLoop.main.run()
输出:
所以我用下面的代码测试
START===================================
1507965166992
109998
1507965173888
END===================================
START===================================
1507965176993
109998
1507965183890
END===================================
START===================================
1507965186989
当我减去先前循环的结束时间和电流回路的开始时间,我总是在3秒左右。但是我已经指定了5秒。这是为什么?
'Timer'用于在特定的时间或重复与指定时间间隔的执行来执行代码。 G.C.D用于多线程。你的解决方案与它有什么关系? – unknownymouse
通过使用GCD我们也可以轻松处理函数的执行.. !! –
但是如何?你能提供一段代码来模拟GCD中的定时器功能吗? – unknownymouse