Heroku's cron jobs are just that, jobs that run on a periodic basis. The free add-on runs daily, the premium add-on (at a whopping $3 a month) runs hourly. You'd be doing yourself and your application a disservice if you didn't take advantage of at least the free version; there's always some cleanup or background housekeeping you ought to do to ensure everything continues to hum along nicely in your application. I have at least half a dozen other daily tasks I plan on rolling in but for the time being I'm using the hook to clear out stale sessions and back up my application's database to S3.

Clearing Out Stale Sessions

Obviously if you're using Rails' default cookie session store then the following does not apply. If however for specific reasons you're using active record to persist your application's session, it's good practice to clear stale sessions from the database. This is good for two reasons. First, less data bloat pleases the application performance gods. Second, a smaller data footprint ensures you're paying the least amount possible for hosting as included in Heroku's pricing model is database storage size and demand. There's a handful of ways to accomplish this but I like to keep things simple hence what follows is about as straightforward as you can get. Looking at this now I'm going to make a tweak to pass in the stale time as an argument to the rake task but nonetheless the snippet below gets the point across:

Backing Up An Application’s Database (To S3)

Heroku provides a few ways to backup your database. There’s bundles which effectively creates a tarball of your code and data. The free version of the add-on permits you to store a single tarball at a time while the premium version (at $20 a month) enables you to store an unlimited number of tarballs. The assumption is you’ll have some process outside of Heroku to do something with this bundle. Alternatively, you can focus entirely on the data as it’s most likely the case your managing your code elsewhere and not relying solely on Heroku’s Git instance. For this, Heroku provides a nice hook to pull your database down into YAML and again, the assumption is you’ll have some process outside of Heroku to take advantage of this.

Both options are fine but not having an automated process to facilitate backing up your application is a bit cumbersome. Sounds like we have another task for cron! In this instance, what I’d like to do is dump the data from my database into YAML, then push that compressed YAML file to S3. Below is the rake task that handles this. This was inspired by another developer’s task I stumbled on which I forked add made some minor tweaks of my own:

So now our Cron rake tasks looks like this (I run the database to S3 dump weekly):