Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some sort of Ruby "Interrupt"

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

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?

All help is appreciated and thanks in advance!

like image 391
adam_0 Avatar asked Dec 21 '22 22:12

adam_0


1 Answers

You have several solutions. One is to use a Thread::Queue if you expect many signals and want to process each of them as an event, for example. If you are really just waiting for ^C to happen with no complex interactions with other threads, I think it may be simple to use Thread#wakeup:

c = Thread.current

Signal.trap("SIGINT") do
  c.wakeup
end

while true
  sleep
  puts "wake"
end
like image 127
Jean Avatar answered Feb 23 '23 22:02

Jean