Skip to contents

Create a 'Watcher' on a filesystem location to monitor for changes in the background.

Usage

watcher(path = getwd(), callback = NULL, latency = 1)

Arguments

path

Character path to a file, or directory to watch recursively. Defaults to the current working directory.

callback

A function or formula (see rlang::as_function), which takes at least one argument. It will be called back with a character vector comprising the paths of all files that have changed. The default, NULL, causes the paths that have changed to be written to stdout instead.

latency

Numeric latency in seconds for events to be reported or callbacks triggered. The default is 1s.

Value

A 'Watcher' R6 class object. Start and stop background monitoring using the $start() and $stop() methods - these return a logical value whether or not they have succeeded.

Details

Uses the optimal event-driven API for each platform: 'ReadDirectoryChangesW' on Windows, 'FSEvents' on MacOS, 'inotify' on Linux, 'kqueue' on BSD, and 'File Events Notification' on Solaris/Illumos.

Note: the latency setting does not mean that changes are polled for at this interval, these still rely on the optimal platform-specific monitor. The implementation of 'latency' is also platform-dependent.

Events are 'bubbled' such that a single change that triggers multiple event flags will cause the callback to be called only once.

It is possible to set a watch on a path that does not currently exist, and it will be monitored once created.

Examples

w <- watcher(tempdir())
w$start()
w
#> <Watcher>
#>   Public:
#>     initialize: function (path, callback, latency) 
#>     path: /tmp/RtmpAWSVus
#>     running: TRUE
#>     start: function () 
#>     stop: function () 
#>   Private:
#>     watch: externalptr
w$stop()
w
#> <Watcher>
#>   Public:
#>     initialize: function (path, callback, latency) 
#>     path: /tmp/RtmpAWSVus
#>     running: FALSE
#>     start: function () 
#>     stop: function () 
#>   Private:
#>     watch: externalptr

Sys.sleep(1)