Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ManickYoj/8cb60d18671f0c98139edc02ce3ce014 to your computer and use it in GitHub Desktop.
Save ManickYoj/8cb60d18671f0c98139edc02ce3ce014 to your computer and use it in GitHub Desktop.
def uninterruptable_operation(iteration)
puts "[INFO #{Time.now}] Start operation, iteration #{iteration}. Part " \
"one: Eg. we might long poll for messages here"
sleep(5)
puts "[INFO #{Time.now}] Operation part two. Eg. we might process " \
"messages here."
sleep(1)
puts "[INFO #{Time.now}] Operation part three. Eg. we might acknowledge " \
"the message as processed here."
sleep(1)
puts "[INFO #{Time.now}] Operation, iteration #{iteration}, complete."
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
iteration = 0
begin
# Main loop
while true
thread = Thread.new{ uninterruptable_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
# 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
rescue SignalException => e
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
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment