Skip to content

Instantly share code, notes, and snippets.

@Epictetus
Forked from rtekie/heroku_manager.rb
Created August 26, 2012 01:29
Show Gist options
  • Save Epictetus/3472982 to your computer and use it in GitHub Desktop.
Save Epictetus/3472982 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::Client.new(HEROKU_USERNAME, HEROKU_PASSWORD)
end
def stack
heroku.list_stacks(HEROKU_APP_NAME).inject("") do |current,stack|
stack["current"] ? stack["name"] : current
end
end
def get_workers
if stack == "cedar"
heroku.ps(HEROKU_APP_NAME).count { |p| p["process"] =~ /worker\.\d?/ }
else
heroku.info(HEROKU_APP_NAME)[:workers].to_i
end
end
def set_workers(count)
if stack == "cedar"
heroku.ps_scale(HEROKU_APP_NAME, :type => 'worker', :qty => count)
else
heroku.set_workers(HEROKU_APP_NAME, count)
end
end
end
# This gist is documented at http://ctoinsights.wordpress.com/2011/11/26/running-heroku-workers-only-when-required/
class GenericJob
@@jobs_running = 0
def initialize
@@jobs_running += 1
if Rails.env.production? and (@@jobs_running == 1)
@heroku ||= HerokuManager.new
@heroku.set_workers(1)
end
end
def perform; end
def after(job)
@@jobs_running -= 1
if Rails.env.production? and (@@jobs_running <=0)
@heroku ||= HerokuManager.new
@heroku.set_workers(0)
end
end
def self.job_count
@@jobs_running
end
end
class TestJob < GenericJob
def perform
message = "#{Time.now} Test"
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