Last active
September 28, 2015 05:58
-
-
Save rtekie/1395677 to your computer and use it in GitHub Desktop.
Running Heroku workers only when required
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
# 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 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
# 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