Reputation: 6895
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
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
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