Creating Cron Jobs for Rails Apps Using the Whenever Gem

By May 9, 2019 General, Tutorial

In this post, we will review the basics of creating and using cron jobs, otherwise known as scheduled tasks in rails apps. First, we will need the whenever gem. We can install it as we would any other gem:

gem install whenever

But, since we are using it in a rails app, we should add it to our gemfile:

gem 'whenever', require: false

Then run: bundle install to install the gem. Now, in your project’s root directory, run: wheneverize .. This command will create a ‘schedule.rb’ file in your config directory. Now we’re all set up to make our first cron job. In our schedule.rb file add the following code:

every 1.minutes do
  runner "Welcome.say_hello"

Now we have a cron job that will run the method Welcome#say_hello every minute. Let’s generate a model to test our cron job:

rails g model Welcome

In our model file welcome.rb add the following method:

def say_hello
  puts "Hello!"

Now we must perform one last step before we can test our cron job. Run the command: whenever --update-crontab in your application directory. This will install the cron jobs in our schedule.rb file. Now when we run our app: rails s, every minute we should see “Hello!” in our console. Thanks for reading! I hope this guide is useful. If you run into any problems or have anything else to say feel free to comment below!

Leave a Reply