+10

How to add schedule auto run rake task to rails

I. Introduction

  • Sometimes, we must to run some task with schedule. Rails support us to do this by gem "whenerver" and rake task.
  • Rake task will make somethings you want to do and it repeat manytimes, so you must to run rake task instead of rewrite your code.
  • Gem "whenever" will make schedule to run your task auto and repeat.

II. Installation

Firstly, we need to install gem "whenever":

  • Add to Gemfile
gem "whenever"
  • Run command bundle install

III. Simple example

In this example, we want to create some notice to do to user every 2 days to remind their work. Then, we need to create a rake task and a schedule to do rake task:

1. Create rake task

We need to generate rake task by this command:

rails g task todos auto_create
create lib/tasks/todos.rake

It will generate our new rake task in file lib/tasks/todos.rake with the contents:

namespace :todos do
  desc "TODO"
  task :auto_create => :environment do
  end
end

Then, we need to add somethings we want to do in this task:

namespace :todos do
  desc "Auto Register ToDo"
  task auto_create: :environment do
    User.visible.each do |user|
      user.to_dos.create comment: "somethings to do"
    end
  end
end

By this way, we have a rake task to create to do for all user when run this command:

rake todos:auto_create

2. Create schedule to run rake task auto

Getting started with those command:

cd /apps/my-great-project
wheneverize .

After that, it will create an initial file: config/schedule.rb

In this file, you can create schedule easily by this simple code:

every 2.days do
  rake "to_dos:auto_create"
end

That's enough for our simple example, but whenever gem can do more.

IV. More about whenever gem

  • If include require: false after gem "whenever" on Gemfile, the gem will be installed, but won't be loaded into a process unless you explicitly call require "whenever".
  • It has many way to create schedule in the time you want, for example:
every 1.day, at: "5:00am" do
    //something
end
every 5.minutes do
    //something
end
every :hour do
    //something
end
every :weekday do
    //something
end
every :monday, at: "8:00am" do
    //something
end
every :reboot do
    //something
end

Or you can use this format:

every "* * * * *" do
    //something
end

with meaning:

  • min (0 - 59)
  • hour (0 - 23)
  • day of month (1 - 31)
  • month (1 - 12)
  • day of week (0 - 6) ~ (sunday = 0)

V. Conclusion

This is a good way to run some tasks auto and repeat with schedule in rails. I hope you find this article useful. Thanks for reading!


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí