简体   繁体   English

Ruby on Rails中的Cron任务

[英]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. 我是Ruby on Rails的新手,我想执行一些定期任务,但是我发现我不知道如何在RoR中设置任何cron任务。 Is there any basic tutorial how to set up cron in RoR? 有任何基本的教程如何在RoR中设置cron吗? Currently I'm running RoR on Webbrick with Mysql DB on Windows platform. 目前,我正在Windows平台上的Webbrick和Mysql DB上运行RoR。

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 . 如果要使用Cron,将其与Rails一起使用的最佳方法是whenever使用gem。 To find out more about whenever, and a quick tutorial on how to use it, check this Railscast Episode 164 . 要查找有关何时使用的更多信息以及如何使用它的快速教程,请查看此Railscast第164页 Cron best suits when you have actions that need to be run every constant time interval (eg. emptying your users' trashes) 当您有需要在每个固定时间间隔运行的操作(例如,清空用户的垃圾桶)时,Cron最适合

  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. 您还可以使用DelayedJob ,它最适合于您的某些操作会持续很长时间并且您不希望用户等到他们的操作完成(例如,当您发送大量电子邮件时)或想要在其中执行某些操作时X小时。 More about DelayedJob you will find here: https://github.com/collectiveidea/delayed_job 有关DelayedJob的更多信息,您将在这里找到: https : //github.com/collectiveidea/delayed_job

  3. You can also Resque with Redis: https://github.com/blog/542-introducing-resque 您还可以使用Redis进行Resque: 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 例如, https://github.com/DAddYE/foreverb

For minimal setup of "cron-like" tasks in "core" rails/ruby, I created https://github.com/Ebbe/arask 为了在“核心” rails / ruby​​中最小化“类似cron”的任务的设置,我创建了https://github.com/Ebbe/arask

No need to install anything (other than the gem) or setup anything outside of rails. 无需安装任何东西(gem除外)或在滑轨之外进行任何设置。

Add gem 'arask' to your Gemfile, run bundle install , rails generate arask:install and rails db:migrate . gem 'arask'添加到您的Gemfile中,运行bundle installrails generate arask:installrails db:migrate

Now you can setup your tasks in the file config/initializers/arask.rb: 现在,您可以在文件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. 如果服务器正在运行,任务将自动运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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