在Ruby中观察Windows上的修改文件

时间:2011-06-08 19:13:45

标签: ruby windows

我正在使用Win32-utils gems在ruby中编写Windows服务。该服务目前有效,但其功能的很大一部分要求它知道文件何时被修改。我目前正在使用包含有关每个文件的数据的大型哈希来执行此操作,这对于相对较小的目录非常有用,但是当在包含~50000个文件的文件夹上使用时,这会占用大量内存并且需要很长时间来检查更新。

代码如下所示:

首先运行(设置哈希):

Find.find(@local_base) do |path|
  # Don't keep any directories in the hash
  if not FileTest.directory?(path)
    f = open(path)
    f.rewind
    @files[path.gsub(@local_base, "")] = DataFile.new(@local_base,
        path.gsub(@local_base, ""),
        Digest::MD5.hexdigest(f.read.gsub("\n", "\r\n")),
        f.mtime.to_i,
        @last_checked)
  end
end

后续运行(检查更新):

def check_for_updates
  # can't/shouldn't modified a hash while iterating, so set up temp storage
  tempHash = Hash.new

  Find.find(@local_base) do |path|

    # Ignore directories
    if not FileTest.directory?(path)
      File.open(path) do |f|
        #...and the file is already in the hash...
        if not @files[path.gsub(@local_base, "")].nil?
          # If it's been modified since the last scan...
          if f.mtime.to_i > @last_checked
            #...and the contents are modified...
            if @files[path.gsub(@local_base, "")].modified?
              #...update the hash with the new mtime and checksum
              @files[path.gsub(@local_base, "")].update
            end
          end # mtime check
        else
          # If it's a new file stick it in the temporary hash
          f.rewind
          tempHash[f.path] = DataFile.new(@local_base,
              path.gsub(@local_base, ""),
              Digest::MD5.hexdigest(f.read.gsub("\n", "\r\n")),
              f.mtime.to_i,
              @last_scan)
        end # nil check
      end # File.open block
    end # directory check
  end # Find.find block

  # If any new files are in the tempHash, add them to @files      
  if not tempHash.empty?
    tempHash.each do |k, v|
        @files[k] = v
    end
  end

  # clear tempHash and update registry    
  tempHash = nil
  update_last_checked
end

是否有更快/更有效的方式来通知我的程序修改过的文件,如果我能在不递归搜索整个目录的情况下做到这一点,那就更好了。

2 个答案:

答案 0 :(得分:1)

如果 change journal 被修改,您可以将其保留给Windows以警告您。 gem 可以“监听”该服务。

答案 1 :(得分:0)

结帐rstakeout.rb。它会以递归方式查看目录,但看起来它会以不同方式检查文件修改标准。我不确定大文件集的速度,但也许它会给你一些想法。

相关问题