I have an application which requires Heroku workers for a small percentage of time. Keeping workers running all the time in such scenario is not cost effective.

HireFire provides a service for managing Heroku resources. I participated in its beta, came out impressed and I would not hesitate to recommend it to others. What I needed however was something even simpler.

Here is the solution:

Heroku provides an api which allows, among many other things, to control number of workers. You will need to add:

gem 'heroku-api'

to your Gemfile. Code below takes advantage of the api. Please note that the code works only with the Cedar stack.

The application uses Delayed_job gem and delayed jobs require a heroku worker to run. Here is the logic:

1. When a delayed job is started it checks if a worker is running. If it is not, a worker is launched.

2. When a job ends it checks if it is the last job running, If it is, the worker is terminated by setting the worker count to 0.

Here is the code:

This is it. Pretty simple.

Advertisements