Donnerstag, 4. April 2013

Spin Heroku Dynos up and down programmatically

Does your customers sleep at night?
If they do, your software can do that as well ;-)

So why not spin the Heroky dynos down to 1 in the night and spin it up next morning again. One dyno is free of charge and your application will still be accessible with a bit larger load time when your app has „gone to sleep“ (swapped out on disc).
The load time, when in „sleep mode“, is aprox 30 seconds, but when it‘s up and running, it‘s ... up and running and will do so for a while until going back to sleep.
Spinning the dynos up and down programmatically is done with two rake tasks and the „Heroku Scheduler Standard“ add on, which is free of charge!

This is what you have to do:
  1. Add an environment variable „APP_NME“ with the name of your app.

    In the console: heroku config:set APP_NAME=myapp
    Check the settings in heroku.
    In the console: heroku config
  2. Add the gem „heroku-api“ to your gemfile.
Please note, that there is an older gem „herou“ to, but you should use the new one as it covers the new heroku api:
    gem "heroku-api", "~> 0.3.9"
  3. As you have to - once in a life time - manually confirm the billing of a second dyno, you have to spin up the dynos to more than 1, manually once.
    In the console: heroku ps:scale web=2
  4. Add the two rake tasks below to lib/tasks/scheduler.rake

    Please note that the heroku scheduler expects a file with the name „scheduler.rake“
    You find your heroku api key in the app settings on heroku!
  5. Add the free heroku add on „Heroku Scheduler Standard“ to your app.

    On the console: 
heroku addons:add scheduler:standard
  6. Test your rake tasks manually.
    In the console: heroku run rake spin_up
    And check the result.
    In the console: heroku ps
  7. Enter the appropriate settings in the heroku scheduler using the heroku web site.
    Please note, that the time entered is a UTC-Time (Coordinated Universal Time), which can differ from your local time. In most european countries the local time is UTC+1 in the winter and UTC+2 in the summer due to the summer time correction.

Content of lib/tasks/scheduler.rake

require 'heroku-api'
desc "Scale UP dynos. This task is called by the Heroku scheduler"
task :spin_up => :environment do
  puts "Spinn one dyno up..."
  heroku = => 'my_app_key')
  heroku.post_ps_scale(ENV['APP_NAME'], 'web', 2)
  puts "Done!"

desc "Scale DOWN dynos. This task is called by the Heroku scheduler"
task :spin_down => :environment do
  puts "Spinn one dyno down..."
  heroku = => 'my_app_key')
  heroku.post_ps_scale(ENV['APP_NAME'], 'web', 1)
  puts "Done!"

Keine Kommentare:

Kommentar veröffentlichen