Search code examples
rmonitoringreal-time

monitoring for changes in file(s) in real time


I have a program that monitors certain files for change. As soon as the file gets updated, the file is processed. So far I've come up with this general approach of handing "real time analysis" in R. I was hoping you guys have other approaches. Maybe we can discuss their advantages/disadvantages.

monitor <- TRUE
start.state <- file.info$mtime # modification time of the file when initiating

while(monitor) {
  change.state <- file.info$mtime
  if(start.state < change.state) {
    #process
  } else {
    print("Nothing new.")
  }
  Sys.sleep(sleep.time)
}

Solution

  • Similar to the suggestion to use a system API, this can be also done using qtbase which will be a cross-platform means from within R:

    dir_to_watch <- "/tmp"
    
    library(qtbase)
    fsw <- Qt$QFileSystemWatcher()
    fsw$addPath(dir_to_watch)
    
    id <- qconnect(fsw, "directoryChanged", function(path) {
      message(sprintf("directory %s has changed", path))
    })
    
    cat("abc", file="/tmp/deleteme.txt")