Scheduling Jobs Using Cron and Whenever

Tutorial 4 of 5

1. Introduction

1.1 Brief Explanation of the Tutorial's Goal

In this tutorial, our goal is to provide you with an understanding of how to schedule jobs using Cron and the Whenever gem. We will guide you on how to set up tasks to run at regular intervals in your Rails application.

1.2 What You Will Learn

By the end of this tutorial, you will be able to:
- Understand what Cron and the Whenever gem are
- Set up and use Cron on your system
- Install and use the Whenever gem in a Rails application
- Schedule tasks to be performed at regular intervals

1.3 Prerequisites

To follow this tutorial, you will need:
- Basic understanding of Ruby on Rails
- Rails installed on your system
- Basic knowledge of UNIX/Linux commands

2. Step-by-Step Guide

2.1 Cron

Cron is a time-based job scheduler used in Unix-like operating systems. Users can schedule tasks (or jobs) to run periodically at fixed times, dates, or intervals.

To view your cron jobs, you can use the command crontab -l. To edit your cron jobs, use crontab -e.

2.2 Whenever gem

Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.

You can install the Whenever gem by adding it to your Gemfile:

gem 'whenever', require: false

And then execute:

$ bundle install

3. Code Examples

3.1 Cron Example

Here is a simple example of a cron job that runs a script every day at 3:30 AM:

30 3 * * * /path/to/script.sh

3.2 Whenever Example

Here is how you can schedule a task with Whenever:

First, you need to run the command below to generate a schedule file:

$ wheneverize .

This will create a config/schedule.rb file in your Rails app. You can define your tasks in this file like so:

every 1.day, at: '4:30 am' do
  runner "MyModel.task_to_run"
end

4. Summary

In this tutorial, we learned about Cron, a time-based job scheduler, and the Whenever gem, which provides a simple syntax for writing cron jobs in Ruby. We also learned how to set up and use these tools to schedule tasks in a Rails application.

5. Practice Exercises

Try these exercises to further solidify your understanding:
1. Schedule a cron job that runs a script every Monday at 5 PM.
2. Use the Whenever gem to schedule a task that runs every 2 days at 6:30 AM.
3. Schedule a cron job that runs a script every hour.

Answers:
1. Cron job:
bash 0 17 * * MON /path/to/script.sh
2. Whenever task:
ruby every 2.day, at: '6:30 am' do runner "MyModel.task_to_run" end
3. Cron job:
bash 0 * * * * /path/to/script.sh