Skip to content

Instantly share code, notes, and snippets.

@dux
Last active September 29, 2015 15:16
Show Gist options
  • Save dux/c00b09622acca6fb45c2 to your computer and use it in GitHub Desktop.
Save dux/c00b09622acca6fb45c2 to your computer and use it in GitHub Desktop.
class Runner
@threads = {}
def self.spawn(name, ttl=1)
@threads[name] = {}
Thread.new do
while @threads[name]
yield(@threads[name])
sleep ttl
end
end
end
def self.kill(name)
@threads.delete(name)
end
end
Runner.spawn :test do |opts|
opts[:cnt] ||= 0
opts[:cnt] += 1
puts "Ding! #{Time.now.to_s} #{opts[:cnt]}"
end
Runner.spawn :killer, 2 do |opts|
opts[:cnt] ||= 0
opts[:cnt] += 1
puts "DONG! #{Time.now.to_s} #{opts[:cnt]}"
if opts[:cnt] == 3
Runner.kill :test
puts "KILLED"
end
end
Ding! 2015-09-29 17:14:23 +0200 1
DONG! 2015-09-29 17:14:23 +0200 1
Ding! 2015-09-29 17:14:24 +0200 2
Ding! 2015-09-29 17:14:25 +0200 3
DONG! 2015-09-29 17:14:25 +0200 2
Ding! 2015-09-29 17:14:26 +0200 4
DONG! 2015-09-29 17:14:27 +0200 3
KILLED
DONG! 2015-09-29 17:14:29 +0200 4
DONG! 2015-09-29 17:14:31 +0200 5
DONG! 2015-09-29 17:14:33 +0200 6
DONG! 2015-09-29 17:14:35 +0200 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment