[英]Ruby on rails: thread execution and logging
假设我有一个用户模型,当我创建一个新的用户模型时,我在创建用户后产生了一个新线程,该线程需要执行一些联网/后台任务。
def create
@user = User.new(params[:user])
collect_info_async(@user)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User created.' }
else
format.html { render action: "new" }
end
end
end
def collect_info_async(user)
Thread.new do
logger.info "Thread starting" #Gets logged correctly
#Do some network requests, perform calculations, etc.
usr = User.find_by_id(user.id).update_attributes(:info => gathered_info)
logger.info "Thread finishing"
end
end
创建新用户时,在日志中会看到“线程正在启动”,但是在真正完成的同时我看不到“线程正在完成”。 我必须从控制台执行User.find或在一段时间后刷新用户页面,然后才能看到“线程完成”日志。 那么异步任务什么时候才能真正完成呢? 并且使用线程是正确的选择吗? 我正在使用Ruby 1.9.3和Rails 3.2.8。
目前,最好在Rails中对后台作业使用专用的工作进程,而不是使用线程。 您可以使用Sidekiq,Resque,delayed_job等。RailsCasts对此有一些不错的截屏视频。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.