rails ruby 中的 Cronjob
Cronjob in ruby on rails
在 rails 的 ruby 中创建一个 cronjob,只要 gem.
set :environment, "development"
set :output, {:error => "log/cron_error_log.log" , :standard => "log/cron_log.log" }
every '* * * * * ' do
command "puts 'you can use raw cron syntax too'"
end
同时更新 crontab,它也添加到 crontab 列表中。但是当我通过
手动测试它时
/home/haseebahmad/projects/social/config/schedule.rb
它给出错误
/home/haseebahmad/projects/social/config/schedule.rb: line 19: every: command not found
/home/haseebahmad/projects/social/config/schedule.rb: line 20: puts 'you can use raw cron syntax too': command not found
/home/haseebahmad/projects/social/config/schedule.rb: line 21: end: command not found
不能正常使用,请问如何解决
我建议将您的 ruby commands/scripting 移至抽佣任务。
这样你就可以通过 rake 测试 ruby 命令是否正常工作,即 ruby 东西由 rake 处理。
那么你只需要运行 cron 作业中的rake 命令。所以你不需要测试 cron ,这是一个痛苦的屁股。
不过,有一些方法可以在 Rails 环境中执行 运行 计划任务,例如script/runner
和Rake
等,其中rake方法超级简单方便,也得到了heroku等流行部署平台的支持。
要定义 rake 任务,您需要在 Rails 应用程序的 lib/tasks
目录中创建一个文件:lib/tasks/my_cron.rake
并像这样简单地定义任务:
task :my_cron => :environment do
puts "doing stuff...."
SomeClass.do_some_stuff
puts "done."
end
然后,对于 运行 这个 rake 任务,你可以从命令行 运行 这个 rake 命令:
rake my_cron
你可以 运行: rake -T
命令来查看你的 Rails 应用程序中所有可用的 rake 任务,如果你像这样提供 desc
rake 任务:
desc 'Running my cron task...'
task :my_cron => :environment do
puts "doing stuff...."
SomeClass.do_some_stuff
puts "done."
end
然后,当你运行这个:rake -T
,这个rake任务将出现在rake任务列表中!
可以很容易地在 heroku 上安排这些 rake 任务
当 rake 任务运行良好时,可能会出现您可能希望在后台处理大量作业的情况,在这些情况下,可以使用几个最流行的 ruby gem resque and sidekiq , 根据您的需要。
在 rails 的 ruby 中创建一个 cronjob,只要 gem.
set :environment, "development"
set :output, {:error => "log/cron_error_log.log" , :standard => "log/cron_log.log" }
every '* * * * * ' do
command "puts 'you can use raw cron syntax too'"
end
同时更新 crontab,它也添加到 crontab 列表中。但是当我通过
手动测试它时/home/haseebahmad/projects/social/config/schedule.rb
它给出错误
/home/haseebahmad/projects/social/config/schedule.rb: line 19: every: command not found
/home/haseebahmad/projects/social/config/schedule.rb: line 20: puts 'you can use raw cron syntax too': command not found
/home/haseebahmad/projects/social/config/schedule.rb: line 21: end: command not found
不能正常使用,请问如何解决
我建议将您的 ruby commands/scripting 移至抽佣任务。
这样你就可以通过 rake 测试 ruby 命令是否正常工作,即 ruby 东西由 rake 处理。
那么你只需要运行 cron 作业中的rake 命令。所以你不需要测试 cron ,这是一个痛苦的屁股。
不过,有一些方法可以在 Rails 环境中执行 运行 计划任务,例如script/runner
和Rake
等,其中rake方法超级简单方便,也得到了heroku等流行部署平台的支持。
要定义 rake 任务,您需要在 Rails 应用程序的 lib/tasks
目录中创建一个文件:lib/tasks/my_cron.rake
并像这样简单地定义任务:
task :my_cron => :environment do
puts "doing stuff...."
SomeClass.do_some_stuff
puts "done."
end
然后,对于 运行 这个 rake 任务,你可以从命令行 运行 这个 rake 命令:
rake my_cron
你可以 运行: rake -T
命令来查看你的 Rails 应用程序中所有可用的 rake 任务,如果你像这样提供 desc
rake 任务:
desc 'Running my cron task...'
task :my_cron => :environment do
puts "doing stuff...."
SomeClass.do_some_stuff
puts "done."
end
然后,当你运行这个:rake -T
,这个rake任务将出现在rake任务列表中!
当 rake 任务运行良好时,可能会出现您可能希望在后台处理大量作业的情况,在这些情况下,可以使用几个最流行的 ruby gem resque and sidekiq , 根据您的需要。