Skip to content

Instantly share code, notes, and snippets.

@andrius
Last active March 20, 2017 11:32
Show Gist options
  • Save andrius/8d617e80027defbfd694124a392f2c7a to your computer and use it in GitHub Desktop.
Save andrius/8d617e80027defbfd694124a392f2c7a to your computer and use it in GitHub Desktop.
# terminate block.call after given timeout
# https://github.com/crystal-lang/crystal/issues/2990
module Timeout
def self.timeout(terminate_after : Float64, &block)
ch = Channel(Bool).new
spawn do
sleep terminate_after
ch.close
end
spawn do
block.call
ch.send true
end
ch.receive rescue false
end
end
# usage
# https://play.crystal-lang.org/#/r/1qeg
Timeout.timeout(2.0) do
sleep 1
puts "1"
sleep 1
puts "2"
end
puts "3"
# live sample
events = [] of String
tcp_conn = TCPSocket.new("127.0.0.1", 5000)
Timeout.timeout(10.0) do
loop do
next_line = tcp_conn.gets rescue ""
break if next_line.to_s.empty?
if next_line
event.push next_line
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment