我正在尝试进行批处理,该处理将采用指定后台工作程序数的参数,并将集合拆分为多个数组。例如,如果
def split_for_batch(number_of_workers)
<code>
end
array = [1,2,3,4,5,6,7,8,9,10]
array.split_for_batch(3)
=> [[1,2,3],[4,5,6],[7,8,9,10]]
问题是我不想一次将所有用户加载到内存中,因为它是一个批处理。我现在拥有的是
def initialize_audit_run_threads
total_users = tax_audit_run_users.count
partition_size = (total_users / thread_count).round
tax_audit_run_users.in_groups_of(partition_size).each do |group|
thread = TaxAuditRunThread.create(:tax_audit_run_id => id, :status_code => 1)
group.each do |user|
if user
user.tax_audit_run_thread_id = thread.id
user.save
end
end
end
其中thread_count是确定后台工作者数量的类的属性。目前这段代码将创建4个线程而不是3.我也尝试使用find_in_batches但是我遇到了同样的问题,如果我在数组中有10个tax_audit_run_users我无法让最后一个工作人员知道处理最后一条记录。在红宝石或铁轨中有没有办法将一个集合分成n个部分,最后一部分是否包括散步者?
答案 0 :(得分:1)
How to split (chunk) a Ruby array into parts of X elements?
你当然需要稍微修改它以添加最后一个块,如果它小于块大小,或者不是,直到你。