简体   繁体   中英

Cron tasks in Ruby on Rails

I'm new to Ruby on Rails, and I wanted to perform some periodical tasks but I found out that I didn't know how to set up any cron task in RoR. Is there any basic tutorial how to set up cron in RoR? Currently I'm running RoR on Webbrick with Mysql DB on Windows platform.

There are few ways to solve your problem.

  1. If you want to use Cron, the best way of using it with Rails is to use a gem whenever . To find out more about whenever, and a quick tutorial on how to use it, check this Railscast Episode 164 . Cron best suits when you have actions that need to be run every constant time interval (eg. emptying your users' trashes)

  2. You can also use DelayedJob which best suits when you have some actions that last long time and you don't want your user wait until their actions finish (eg. when you deliver a lot of emails) or when you want to take some actions in X hours. More about DelayedJob you will find here: https://github.com/collectiveidea/delayed_job

  3. You can also Resque with Redis: https://github.com/blog/542-introducing-resque

You can create a daemon script, which always be in memory.
For example, https://github.com/DAddYE/foreverb

For minimal setup of "cron-like" tasks in "core" rails/ruby, I created https://github.com/Ebbe/arask

No need to install anything (other than the gem) or setup anything outside of rails.

Add gem 'arask' to your Gemfile, run bundle install , rails generate arask:install and rails db:migrate .

Now you can setup your tasks in the file config/initializers/arask.rb:

arask.create task: 'send:logs', cron: '0 2 * * *' # At 02:00 every day
arask.create script: 'puts "IM ALIVE!"', interval: :daily
arask.create task: 'my:awesome_task', interval: :hourly
arask.create task: 'my:other_awesome_task', interval: 2.hours

The tasks will automatically run if the server is running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM