我测试了这个简单的工作,由一名普通的resque工人执行。
class Jobs::TestTempfile
@queue = :test
def self.perform
Tempfile.open('foo') do |f|
puts f.path
end
end
end
创建的临时文件在作业结束后仍然存在,甚至一旦工作人员被终止(kill -QUIT pid
)。
我知道最佳做法是取消链接并关闭所有Tempfiles
,但这似乎是一个问题...是否有人知道某些全球解决方案?或者我是否必须通过所有现有作业手动取消链接Tempfiles
。
我使用ruby 2.1
进行了测试(但我很肯定2.0
)和resque 1.24.1
存在此问题。
谢谢!
答案 0 :(得分:0)
file = Tempfile.new('foo')放置file.path
工作原理并在解释器退出后删除临时文件。
答案 1 :(得分:0)
从我的GitHub答案中复制此内容:
阅读Tempfile文档:
当Tempfile对象被垃圾收集时,或Ruby解释器退出时,其关联的临时文件是 自动删除。这意味着在使用后不必显式删除Tempfile,尽管它很好 这样做的做法:不明确删除未使用的Tempfiles可能会留下大量的临时文件 文件系统,直到它们被垃圾收集。这些临时文件的存在会使得确定更难 新的Tempfile文件名。
GC可能永远不会在工作生命周期中运行,这会使所有的临时文件都存在。在::perform
方法结束时取消链接可能是最佳做法。
您还可以执行以下操作:
class JobWithTempfiles
class << self
def new_tmpfile(name)
file = Tempfile.new(name)
@tmp_files ||= []
@tmp_files << file
end
def perform_with_tmpfile_cleanup
begin
perform_without_tmpfile_cleanup
ensure
@tmp_files.each do |tmpfile|
tmpfile.close
tmpfile.unlink
end
end
end
alias_method_chain :perform, :tmpfile_cleanup
end
end
class JobNeedingATmpFil < JobWithTempfiles
def self.perform_without_tempfile_cleanup
tmp_file = new_tmpfile("foo")
# Do a bunch of stuff
end
end