我想在EventMachine中使用ActiveRecord对大型数据集执行批处理数据库查询。我希望传递给find_each块的每个调用都在 EventMachine 周期计时器中调用。
通过以下方法,find_each只是运行,add_periodic_timer块只运行一次,直到find_each完全完成(即定期计时器块不会每 0.001 秒运行一次):
EventMachine.add_periodic_timer(0.001) do
TradingCore::Quote.by_date(@date).by_symbols(@symbols).order(:created_at).find_each do |quote|
...
sleep(delay)
end
end
有没有办法在不阻塞事件循环的情况下为每个记录执行find_each块?
我想我用纤维解决了这个问题。所以,我这样做了
quotes_fiber = Fiber.new {
TradingCore::Quote.by_date(@date).by_symbols(@symbols).order(:created_at).find_each do |quote|
...
sleep(delay)
Fiber.yield
end
}
EventMachine.add_periodic_timer(0.001) do
quotes_fiber.resume
end
事情似乎进展顺利:)