- 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.
Firstly, we need to install gem "whenever":
- Add to
- Run command
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:
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:
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
Gemfile, the gem will be installed, but won't be loaded into a process unless you explicitly call
- 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
- min (0 - 59)
- hour (0 - 23)
- day of month (1 - 31)
- month (1 - 12)
- day of week (0 - 6) ~ (sunday = 0)
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