A resettable timeout for Ruby
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
require 'redis' | |
@redis = Redis.new | |
@redis.set('timeout', 0) |
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
require 'redis' | |
module Referee | |
class Timeout < StandardError; end | |
class Timer | |
def initialize(key, limit = 5, &block) | |
@redis = Redis.new | |
@key = key | |
@limit = limit | |
@redis.set(@key, @limit) | |
start | |
@work = Thread.new { yield self } | |
@work.join | |
@timer.join if @timed_out | |
end | |
def start | |
@timer = Thread.new do | |
@counter = 0 | |
# TODO: Use promises to make sure we have the limit from redis before | |
# incrementing the counter. | |
loop do | |
@limit = @redis.get(@key).to_i | |
@counter += 1 | |
if @counter > @limit | |
break | |
end | |
sleep(1) | |
end | |
@timed_out = true | |
@work.kill | |
raise Referee::Timeout | |
end | |
end | |
def stop | |
@timer.kill | |
end | |
def reset | |
stop | |
start | |
end | |
end | |
end |
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
require_relative 'referee' | |
begin | |
Referee::Timer.new(5) do |timer| | |
sleep(1) | |
puts "yup" | |
sleep(5) | |
puts "nope" | |
end | |
rescue Referee::Timeout | |
puts "timed out!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment