Skip to content

Instantly share code, notes, and snippets.

@rtekie
Last active September 28, 2015 05:58
Show Gist options
  • Save rtekie/1395677 to your computer and use it in GitHub Desktop.
Save rtekie/1395677 to your computer and use it in GitHub Desktop.
Running Heroku workers only when required
# This gist is documented at http://ctoinsights.wordpress.com/2011/11/26/running-heroku-workers-only-when-required/
class HerokuManager
def heroku
@heroku ||= Heroku::API.new
end
def get_workers
heroku.get_ps(HEROKU_APP_NAME).body.count { |p| p["process"] =~ /worker\.\d?/ }
end
def set_workers(count)
heroku.post_ps_scale(HEROKU_APP_NAME, 'worker', count)
end
end
# This gist is documented at http://ctoinsights.wordpress.com/2011/11/26/running-heroku-workers-only-when-required/
class GenericJob
def initialize
if Rails.env.production?
@heroku ||= HerokuManager.new
@heroku.set_workers(1) if (@heroku.get_workers == 0)
end
end
def perform; end
def after(job)
if Rails.env.production?
@heroku ||= HerokuManager.new
@heroku.set_workers(0) if (job_count == 1)
end
end
def job_count
Delayed::Job.all(:conditions => {failed_at: nil}).length
end
end
class TestJob < GenericJob
def perform
message = "#{Time.now} TestJob completed"
puts message
rescue Exception => e
puts "#{Time.now} ERROR: #{e.message}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment