在Rails环境中运行计划任务的最佳方法是什么?脚本/跑步吗?耙?我想每隔几分钟运行一次任务。
当前回答
我最近为我一直在做的项目创建了一些cron作业。
我发现宝石发条非常有用。
require 'clockwork'
module Clockwork
every(10.seconds, 'frequent.job')
end
你甚至可以使用这个宝石来安排你的后台工作。 有关文档和进一步帮助,请参阅https://github.com/Rykian/clockwork
其他回答
我最近为我一直在做的项目创建了一些cron作业。
我发现宝石发条非常有用。
require 'clockwork'
module Clockwork
every(10.seconds, 'frequent.job')
end
你甚至可以使用这个宝石来安排你的后台工作。 有关文档和进一步帮助,请参阅https://github.com/Rykian/clockwork
无论何时(和cron)的问题是,它每次执行时都会重新加载rails环境,当任务频繁或有大量初始化工作要做时,这是一个真正的问题。由于这个原因,我在生产中出现了问题,必须警告你。
Rufus调度器为我做(https://github.com/jmettraux/rufus-scheduler)
当我有较长的作业要运行时,我使用delayed_job (https://github.com/collectiveidea/delayed_job)
我希望这能有所帮助!
下面是我如何设置我的cron任务。我有一个每天备份SQL数据库(使用rake)和另一个每月过期缓存一次。任何输出都记录在文件log/cron_log中。我的crontab是这样的:
crontab -l # command to print all cron tasks
crontab -e # command to edit/add cron tasks
# Contents of crontab
0 1 * * * cd /home/lenart/izziv. whiskas.si/current; /bin/sh cron_tasks >> log/cron_log 2>&1
0 0 1 * * cd /home/lenart/izziv.whiskas.si/current; /usr/bin/env /usr/local/bin/ruby script/runner -e production lib/monthly_cron.rb >> log/cron_log 2>&1
第一个cron任务每天备份数据库。cron_tasks的内容如下:
/usr/local/bin/rake db:backup RAILS_ENV=production; date; echo "END OF OUTPUT ----";
第二个任务稍后设置,并使用脚本/运行器每月过期一次缓存(lib/monthly_cron.rb):
#!/usr/local/bin/ruby
# Expire challenge cache
Challenge.force_expire_cache
puts "Expired cache for Challenges (Challenge.force_expire_cache) #{Time.now}"
我想我可以用其他方式备份数据库,但到目前为止,它适合我:)
rake和ruby的路径在不同的服务器上可能不同。你可以使用以下命令查看它们的位置:
whereis ruby # -> ruby: /usr/local/bin/ruby
whereis rake # -> rake: /usr/local/bin/rake
你可以使用resque和resque- scheduling gem来创建cron,这很容易做到。
https://github.com/resque/resque
https://github.com/resque/resque-scheduler
在我们的项目中,我们首先使用了无论何时宝石,但遇到了一些问题。
然后我们切换到RUFUS SCHEDULER gem,它在Rails中调度任务时非常简单可靠。
我们已经使用它来发送每周和每天的邮件,甚至运行一些定期的rake任务或任何方法。
这里使用的代码是这样的:
require 'rufus-scheduler'
scheduler = Rufus::Scheduler.new
scheduler.in '10d' do
# do something in 10 days
end
scheduler.at '2030/12/12 23:30:00' do
# do something at a given point in time
end
scheduler.every '3h' do
# do something every 3 hours
end
scheduler.cron '5 0 * * *' do
# do something every day, five minutes after midnight
# (see "man 5 crontab" in your terminal)
end
了解更多:https://github.com/jmettraux/rufus-scheduler
推荐文章
- Ruby:包含的反义词是什么?Ruby数组?
- 想要在Rails中找到没有关联记录的记录
- helper和helper_method做什么?
- 如何回滚只是一个步骤使用耙db:迁移
- 如何传递参数到一个Rake任务与环境在Rails?
- 如何在Rails中计算相对时间?
- 如何在Rails迁移中将可空列更改为不可空列?
- Ruby on Rails -从CSV文件导入数据
- Ruby/Rails:将Date转换为UNIX时间戳
- 如何从URL下载文件并保存在Rails中?
- 如何运行一次cron,每天晚上10点
- Rails:缺少要链接的主机!请提供:host参数或设置default_url_options[:host]
- Rails。env vs RAILS_ENV
- 如何从Ruby数组中创建平均值?
- 我能在视图中得到当前控制器的名称吗?