Last active
May 2, 2020 23:49
-
-
Save lbarasti/dab35d474ff55c68fdbb985a1d6147c9 to your computer and use it in GitHub Desktop.
select use case 3: timeout on async calls
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 log(msg) | |
puts "#{Fiber.current.name}: #{msg}" | |
end | |
Cache = Hash(Symbol, Float64?).new | |
def get_stock_price_async(sym : Symbol) : Channel(Float64) | |
Channel(Float64).new.tap { |ch| | |
spawn do | |
sleep rand | |
ch.send(rand) | |
end | |
} | |
end | |
def get_stock_price(sym : Symbol, max_wait : Time::Span) | |
select | |
when v = get_stock_price_async(sym).receive | |
log "received #{sym} price: #{v}" | |
Cache[sym] = v | |
when timeout max_wait | |
log "timed out, returning cached value for #{sym}" | |
Cache[sym]? | |
end | |
end | |
10.times { | |
log get_stock_price(:apl, 0.5.seconds) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment