Ruby on Rails - 在为 Cron 作业设置的 Rake 任务中使用时区
我的 Web 应用程序需要运行 6 个不同的 cron 作业,以在每个时区的 00:01:00 更新表中的时区敏感数据。我想为每个时区创建 rake 任务。我可以将 rake 任务配置为时区感知吗?例如,我可以在 rake 任务中执行以下操作:
namespace :db do
task :update_EST_records => :environment do
Time.zone = "Eastern Time (US & Canada)"
sql = "UPDATE QUERY GOES HERE WITH CREATED_AT BETWEEN ? AND ?"
ActiveRecord::Base.establish_connection
ActiveRecord::Base.connection.execute(sql,
Time.zone.now.beginning_of_day.utc,
Time.zone.now.end_of_day.utc)
end
end
My web application requires 6 different cron jobs to run to update timezone sensitive data within tables at 00:01:00 of each timezone. I want to create rake tasks for each time zone. Can I configure rake tasks to be timezone aware? For e.g., can I do that following in a rake task:
namespace :db do
task :update_EST_records => :environment do
Time.zone = "Eastern Time (US & Canada)"
sql = "UPDATE QUERY GOES HERE WITH CREATED_AT BETWEEN ? AND ?"
ActiveRecord::Base.establish_connection
ActiveRecord::Base.connection.execute(sql,
Time.zone.now.beginning_of_day.utc,
Time.zone.now.end_of_day.utc)
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,你可以。因为
:update_EST_records
依赖于:environment
任务,所以您可以访问所有 Rails 环境。只要从模型类而不是原始 SQL 运行更新查询,您甚至不必调用 ActiveRecord::Base.assessment_connection。
Yes, you can. Because
:update_EST_records
depends on:environment
task, then you have access to all your Rails environment.You don't even have to call
ActiveRecord::Base.establish_connection
as long as you run the update query from your model class instead of raw SQL.