Rails 3在使用线程时未初始化常量



我正在运行rails 3线程来提高rake任务的性能。有时,当我试图从当前类访问外部类时,会得到未初始化的常量。例如,当我试图从NotificationApp访问NotificationService类时,如下所示,然后将错误作为未初始化的常量NotificationService。并不是每次都会出现这种错误。有时rake任务运行良好,并没有出现错误,有时相同的rake由于未初始化的常量而失败。这可能是什么原因,我该如何解决这个问题?

class NotificationApp < ActiveRecord::Base
def signal_event
NotificationService.notify
end
end

编辑

这就是我创建线程池的方式

class ThreadPool
def initialize(size)
@size = size
@jobs = Queue.new
@pool = Array.new(@size) do |i|
Thread.new do
Thread.current[:id] = i
catch(:exit) do
loop do
job, args = @jobs.pop
job.call(*args)
end
end
end
end
end
# add a job to queue
def schedule(*args, &block)
@jobs << [block, args]
end
# run threads and perform jobs from queue
def run!
@size.times do
schedule { throw :exit }
end
@pool.map(&:join)
end
# get all threads created 
def threads
@pool
end
def complete!
@pool.each{|t| t.kill}
end
end

这就是我使用线程的方式

def perform
ReadReplicaHelper.read_from_slave do
pool = ThreadPool.new(CONNECTION_POOL_COUNT - 1)
device_ids.in_groups_of(1000, false) do |devices|
devices.each do |device_id|
device = Device.find_by_id(device_id)
if device
ReadReplicaHelper.read_from_master do
Notification.where(device_id: device_id).each do |notification|
pool.schedule do
pool_method notification, last_status, before_last_status
end
end
end
end
end
end
# Run the Thread Pool
pool.run!
# Kill the threads created in the pool
pool.complete!
end

确保您的NotificationService类位于名为app/services/notification_service.rb的文件中,并且您正在加载此服务目录。

同样,当您使用线程时,请确保在调用后join所有线程

相关内容

  • 没有找到相关文章

最新更新