Created
June 5, 2012 05:22
-
-
Save ecavazos/2872818 to your computer and use it in GitHub Desktop.
Some defer for that "A"
This file contains hidden or 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 '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