某种Ruby“中断” [英] Some sort of Ruby "Interrupt"
问题描述
所以这里是我正在做的 - 我有一个ruby脚本,每分钟打印出一些信息。我还设置了一个陷阱的进程,以便当用户点击ctrl-c时,进程中止。代码看起来像这样:
So here's what I'm doing -- I have a ruby script that prints out information every minute. I've also set up a proc for a trap so that when the user hits ctrl-c, the process aborts. The code looks something like this:
switch = true
Signal.trap("SIGINT") do
switch = false
end
lastTime = Time.now
while switch do
if Time.now.min > lastTime.min then
puts "A minute has gone by!"
end
end
现在代码本身是有效的,运行良好,但是许多无用的工作经常检查 switch
的价值。它可以使用尽可能多的处理器(至少是一个核心的100%),所以这很浪费。如何进行类似的事情,哪些事件经常更新,而不会浪费大量的周期?
Now the code itself is valid and runs well, but it does a lot of useless work checking the value of switch
as often as it can. It uses up as much of the processor as it can get (at least, 100% of one core), so it's pretty wasteful. How can I do something similar to this, where an event is updated every so often, without wasting tons of cycles?
所有的帮助是感谢,并提前感谢! p>
All help is appreciated and thanks in advance!
推荐答案
如果你只是陷入ctrl-c中断,不要介意按键之间的短暂等待,那么它就会突破。 ..
If you are just trapping ctrl-c interrupts and don't mind a short wait between pressing the keys and it breaking out then...
switch = true
Signal.trap("SIGINT") do
switch = false
end
lastTime = Time.now
while switch do
sleep 1
if Time.now.min > lastTime.min then
puts "A minute has gone by!"
end
end
睡眠功能使用系统计时器,所以等待时不用CPU。如果您想要更精细的分辨率时间,只需将 sleep 1 替换为 sleep 0.5 或更小以减少支票之间的时间,
The 'sleep' function uses the system timers, so doesn't use up the CPU while waiting. If you want finer resolution timing just replace sleep 1 with sleep 0.5 or even smaller to reduce the time between checks,
这篇关于某种Ruby“中断”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!