Creating Simple Automated Jobs in Heroku with Rails and Scheduler

Zayne Abraham
3 min readMar 23, 2018

--

Creating cron jobs in Heroku can be a little confusing at first. When I started building things with ruby, I really liked to use the whenever gem for local projects, as it’s super easy to set up and start running. However, whenever unfortunately isn’t compatible with Heroku.

So you typically have to turn to using something like Sidekiq + Sidekiq-cron or similar tools for recurring background jobs.

Sidekiq is great, but if you’re just trying to run a simple recurring task that can be limited to every 10 minutes, every hour, or every day, Heroku’s Scheduler is a super easy option you can set up in a couple of minutes.

How it Works

to get started with Heroku Scheduler, in your terminal add this command (make sure you’re in the directory of the app you want to add this to):

heroku addons:create scheduler:standard

This will add Scheduler to your app. Then, inside of your /lib/tasks directory add a new file and title it ‘scheduler.rake’:

lib/tasks/scheduler.rake

This is where we’ll be putting the code for our automated jobs to run. So now let’s look at a quick real world example. For my example app, I’m using twitter’s API to automatically pull job listings from my apps database and post tweets of open job listings to the app’s dedicated twitter account every hour. This is done using Heroku’s Scheduler. The core trigger for this functionality is a method ‘fire_tweet’ that exists in a class called TwitterBot, so ‘TwitterBot.fire_tweet’. Knowing this, let’s take a look at how I’ve set up my ‘scheduler.rake’ file in this app:

# lib/tasks/scheduler.rake desc "tweets to twitter.com/blockwork_cc"
task update_twitter_feed: :environment do
puts "Updating @blockwork_cc's twitter feed..."
TwitterBot.fire_tweet
puts "tweet sent!"
end

now with the code added to our rake file, let’s open up scheduler and add the task ‘update_twitter_feed’. In your terminal type in and enter the following:

heroku addons:open scheduler

Now inside of scheduler we can add the new task and set the interval we want it to run at (the default options are every 10 minutes, every hour, and every day). We can do this by adding ‘rake’ and then the name of our rake task:

After adding the task, we can now test it from our terminal to make sure it’s working:

heroku run rake update_twitter_feed

And just like that my job is running in the background every hour like clockwork!

Now get out there and start building a robot army to run your applications for you!

This post originally appeared on: https://zayne.io/

--

--

Zayne Abraham
Zayne Abraham

Written by Zayne Abraham

Read more posts I’m working on about startups, coding, ruby, rails and more here: https://zayne.io