Can the R console support background tasks or interrupts (event-handling)?

☆樱花仙子☆ 提交于 2019-12-04 04:16:20
mbq

It depends whether you want to interrupt idling or working R. If the first, you can think of bypassing the R default REPL loop by some event listener that will queue the incoming events and evaluate them. The common option is to use tcl/tk or gtk loop; I have made something like this around libev in my triggr package, which makes R digest requests coming from a socket.

The latter case is mostly hopeless, unless you will manually make the computational code to execute if(evenOccured) processIt code periodically.

Multithreading is not a real option, because as you know two interpreters in one process will break themselves by using same global variables, while forked processes will have independent memory contents.

One more option is the svSocket package. It is non blocking.

Here is an 8 minute video using it, which has over 3,000 views. It shows how to turn an R session into a server and how to send commands to it and receive data back. It demonstrates doing that even while the server is busy; e.g., say you start a long running process and forget to save intermediate results, you can connect to the server and fetch the results (before it has finished) from it.

It turns out that the package Rdsm supports this as well.

With this package, one can set up a server/client relationship between different instances of R, each is a basic R terminal, and the server can send messages, including functions, to the clients.

Transformed to the use case I described, the server process can do whatever monitoring is necessary, and then send messages to the clients. The documentation is a little terse, unfortunately, but the functionality seems to be straightforward.

If the server process is, say, monitoring a connection (a file, a pipe, a URL, etc.) on a regular basis and a trigger is encountered, it can then send a message to the clients.

Although the primary purpose of the package is shared memory (which is how I came across it), this messaging works pretty well for other purposes, too.


Update 1: Of course for message passing, one can't ignore MPI and the Rmpi package. That may do the trick, but the Rdsm package launches / works with R consoles, which is the kind of interface I'd sought. I'm not yet sure what Rmpi supports.

A few ideas:

  1. Run R from within another language's script (this is possible, for example, in Perl using RSPerl) and use the wrapping script to launch the listener.

  2. Another option may be to run an external (non-R) command (using system()) from within R that will launch a listener in the background.

  3. Running R in batch mode in the background either before launching R or in a separate window.

    For example:

    R --no-save < listener.R > output.out &

    The listener can send an approraite email when the event occurs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!