Cron Jobs in Rails
With the Whenever Gem
Yesterday I wanted to experiment with the whenever gem in ruby and learn a little more about setting up cron jobs in rails. I thought it would be fun to test this out on a Bitcoin API and build a small price tracking app.
After looking at a few options, I decided to use the blockchain.info API as it seemed to be pretty consistent with prices compared against other APIs.
So Let’s Go
First, let’s fire up a new Rails project in the console:
rails new btc_tracker
and add a few necessary gems in our Gemfile, mainly the rest-client gem and the whenever gem.
Then we can add our price model:
rails g model Price price:integer
And a controller to go with it:
rails g controller prices index
and rake db:migrate
Now we can add our main functionality. I put the following into the price model to make a call to the API and store the result in the database:
In the code above we’re creating a variable (blockchain_url) for the api’s url. Then we’re making the request (using the restclient gem we added) and parsing it as JSON.
Once we have the response we’re digging into the hash to get the USD price at the current time. Then we’re creating a new Price instance, setting the price with the data we received from the blockchain.info api, and finally we’re storing it to the database with price.save
Adding the Whenever Gem
Now it’s time to set up the whenever gem. This is actually pretty simple to get up and running in a few minutes!
Once you run through the gem’s basic setup, a schedule file gets generated in your config folder where you can schedule your tasks.
For my btc tracker test, I’m going to store price changes by the minute, and then display the last hour of price data. So I want my get_data method to run every minute. So this is how I’ll add the task for whenever:
Now we can generate and index method in our price controller and an index view to display the data:
Now we can set up the chart.
After digging through some CodePen demos, I found a demo using chart.js that looked like it would be easy to pass my own data to.
To do this, I first put together a little method in my price helper to grab the last 60 records:
Also some quick HTML in our views price index for the chart:
And with that, pit pat piffy wing wong wang, we should now have a simple, functional chart that tracks and updates BTC prices by the minute, displaying the last hour of data: