ADD 定时任务:每晚更新课堂的试卷数量(courses表中的exercises_count字段)

educoder
jasder duan 12 months ago
parent c1a8f932e9
commit 32ff45fcd7

@ -0,0 +1,23 @@
#coding=utf-8
# 通过配置服务器的crontab每天定时头歌平台中之前设置的counter_cache数
# 取消model层面设置的counter_cache回调解决并发场景下锁表锁行的问题
namespace :daily_update_counter_cache_data do
desc "update counter_cache every day "
task :execute => :environment do
# 更课堂中exercises_count字段
courses = Course.joins(:exercises).select("courses.id, COUNT(exercises.id) AS query_exercises_count").group("courses.id").order("query_exercises_count DESC")
courses = courses.where(id: ENV['update_id']) if ENV['update_id'].present?
courses.find_in_batches(batch_size: 10000) do |group|
update_sql = "UPDATE courses SET exercises_count = CASE id "
Parallel.each(group, in_threads: 6) do |course|
update_sql += " WHEN #{course.id} THEN #{course.query_myshixuns_count&.to_i} "
end
update_sql += " ELSE exercises_count END WHERE id IN (#{group.map(&:id).join(',')})"
Rails.logger.info "########## #{Time.now} 更新课堂exercises_count的SQL语句: #{update_sql}"
ActiveRecord::Base.connection.execute(update_sql) if group.present?
end
end
end
Loading…
Cancel
Save