applechief
applechief

Reputation: 6895

How do I interrupt a loop in a command-line script, but only after the method finishes?

I have a Ruby script that looks like:

def big_function
  puts "starting..."
  #does stuff
  puts "done"
end

loop do
  big_function
end

It runs indefinitely, executing big_function.

I need a way for a user to interrupt the running script but never in the middle of big_function. If it is interrupted while big_function is running, it should exit when big_function is done.

Upvotes: 2

Views: 1615

Answers (2)

steenslag
steenslag

Reputation: 80065

Trap does that:

interrupted = false
trap("INT") { interrupted = true } # traps Ctrl-C
puts 'Press Ctrl-C to exit'

def big_function
  puts "starting..."
  sleep 1
  puts "done"
end

until interrupted do
  big_function
end

Upvotes: 4

mabounassif
mabounassif

Reputation: 2341

You could use flags. You can have a separate process polling in the key triggering of the user, and if he clicks or press a key that flag changes state. You will have to check the flag before exiting.

flag = false

t = Thread.new() {
  loop do
    flag = gets
    break if flag
  end
}

def big_function
  puts "starting..."
  #does stuff
  puts "done"
end

loop do
  break if flag
  big_function
end

Upvotes: 2

Related Questions