Skip to content

Instantly share code, notes, and snippets.

@ecavazos
Created June 5, 2012 05:22
Show Gist options
  • Save ecavazos/2872818 to your computer and use it in GitHub Desktop.
Save ecavazos/2872818 to your computer and use it in GitHub Desktop.
Some defer for that "A"
require 'eventmachine'
class HardWorker
def initialize(name)
@name = name
@completion = EM::Completion.new
end
def work
operation = Proc.new {
10.times do |i|
puts "starting job #{@name} - ##{i}"
sleep rand(4)
end
}
callback = Proc.new { @completion.succeed(Time.now) }
EM.defer operation, callback
@completion
end
end
class CompletionCollection
def initialize
@worker_count = 3
@completions = []
end
def run
@worker_count.times do |i|
worker = HardWorker.new "Job#{i}"
@completions << completion = worker.work
completion.callback { |time|
@completions.pop
time_str = time.strftime('%e %b %Y %H:%m:%S%p')
puts "Job#{i} is finished at (#{time_str})."
EM.stop if @completions.empty?
}
completion.errback { puts("Job#{i} failed.") }
end
end
end
EM.run do
CompletionCollection.new.run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment