Last active
April 5, 2022 01:22
-
-
Save ManickYoj/3bf4855d1e51046a679dd04680ea96bb to your computer and use it in GitHub Desktop.
A ruby script that, upon interrupt, delays exit until after a method has completed execution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def operation(iteration) | |
# ... As implemented above | |
end | |
# Only runs if the file is the entry point for execution, | |
# but not if loaded as a library | |
if $0 == __FILE__ | |
puts "[INFO #{Time.now}] #--- Starting Worker Program ---#" | |
thread = nil | |
# This block only runs when the program is about to exit. It waits for | |
# the running thread to complete before continuing with the exit operation | |
at_exit do | |
puts "[WARN #{Time.now}] #--- INTERRUPT RECEIVED ---#" | |
puts "[WARN #{Time.now}] Waiting for current iteration to complete. " \ | |
"Interrupt again for immediate (unsafe) termination." | |
# Wait for the currently running thread to exit before continuing execution | |
thread.join | |
puts "[INFO #{Time.now}] #--- ITERATION COMPLETED. EXITING " \ | |
"SAFELY ---#" | |
end | |
iteration = 0 | |
# Main loop | |
while true | |
thread = Thread.new{ operation(iteration) } | |
# Wait for thread to complete before proceeding. Otherwise, this while | |
# loop would quickly spin up the maximum number of threads all running | |
# concurrently. | |
thread.join | |
iteration += 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment