【发布时间】:2019-10-12 05:10:31
【问题描述】:
我有一个 ruby on rails 应用程序,它每 5 秒根据数据库中创建的新记录发送推送通知。除了 CRON 作业之外,还有什么方法可以在数据库中进行轮询/查询以检查新记录。
我当前的代码实现是每分钟运行一次 CRON,它会休眠 5 秒,但这种方法会消耗大量内存。
schedule.rb #whenever gem file
every 1.minute do
runner "DailyNotificationChecker.send_notifications"
end
* ### 下面的代码每 5 秒调用一次方法 process_notes
def self.send_notifications
expiry_time = Time.now + 57
while (Time.now < expiry_time)
if RUN_SCHEDULER == "true" || RUN_SCHEDULER == true
process_notes #calls method mentioned below
end
sleep 5 #seconds
end
end
### below code check for new records and sends notification
def self.process_notes
notes = nil
time = Benchmark.measure do
Note.uncached do
notes = Note.where("(created_at > DATE_SUB(now(), INTERVAL 2 minute)) AND `notes`.`processed` = 0")
if notes.present?
note_ids = notes.collect{|x| x.id}
RealtimeNotifier.new.delay.perform(note_ids,NOTE_CREATED,TEMP_USER_NOTE)
end
end
end
end
此代码 sn-p 有效,但不是优化的解决方案。有没有更好的方法来实现这一点。
【问题讨论】:
-
或者github.com/Ebbe/arask 可能会更好。在 Arask 配置中添加这一行:
arask.create script: 'DailyNotificationChecker.send_notifications', interval: 5.seconds。这应该让 Rails 每 5 秒自动运行一次任务。
标签: ruby-on-rails ruby ruby-on-rails-4 cron