- Notifications
You must be signed in to change notification settings - Fork32
Schedule an R function or formula to run after a specified period of time
License
Unknown and 2 other licenses found
Licenses found
r-lib/later
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Schedule an R function or formula to run after a specified period oftime. Similar to JavaScript’ssetTimeout function. Like JavaScript, Ris single-threaded so there’s no guarantee that the operation will runexactly at the requested time, only that at least that much time willelapse.
To avoid bugs due to reentrancy, by default, scheduled operations onlyrun when there is no other R code present on the execution stack; i.e.,when R is sitting at the top-level prompt. You can force past-dueoperations to run at a time of your choosing by callinglater::run_now().
The mechanism used by this package is inspired by Simon Urbanek’sbackground package and similar codein Rhttpd.
You can install the development version of later with:
pak::pak("r-lib/later")
Pass a function (in this case, delayed by 5 seconds):
later::later(\() print("Got here!"),5)
Or a formula (in this case, run as soon as control returns to thetop-level):
later::later(~print("Got here!"))
It is also possible to have a function run based on when filedescriptors are ready for reading or writing, at some indeterminate timein the future.
Below, a logical vector is printed indicating which of file descriptors21 or 22 were ready, subject to a timeout of 1s.
later::later_fd(\(x) print(x), c(21L,22L),timeout=1)
This is useful in particular for asynchronous I/O, allowing reads to bemade from TCP sockets as soon as data becomes available. Functions suchascurl::multi_fdset() return the relevant file descriptors to bemonitored.
You can also calllater::later from C++ code in your own packages, tocause your own C-style functions to be called back. This is safe to callfrom either the main R thread or a different thread; in both cases, yourcallback will be invoked from the main R thread.
later::later is accessible fromlater_api.h and its prototype lookslike this:
voidlater(void (*func)(void*), void* data, double secs)
The first argument is a pointer to a function that takes onevoid*argument and returns void. The second argument is avoid* that will bepassed to the function when it’s called back. And the third argument isthe number of seconds to wait (at a minimum) before invoking.
later::later_fd is also accessible fromlater_api.h and itsprototype looks like this:
voidlater_fd(void (*func)(int *,void *), void *data, int num_fds, struct pollfd *fds, double secs)
The first argument is a pointer to a function that takes two arguments:the first being anint* array provided bylater_fd() when calledback, and the second being avoid*. Theint* array will be thelength ofnum_fds and contain the values0,1 orNA_INTEGER toindicate the readiness of each file descriptor, or an error conditionrespectively. The second argumentdata is passed to thevoid*argument of the function when it’s called back. The other requiredarguments are the total number of file descriptors, a pointer to anarray ofstuct pollfd, and the number of seconds to wait until timingout.
To use the C++ interface, you’ll need to addlater to yourDESCRIPTION file under bothLinkingTo andImports, and also makesure that yourNAMESPACE file has animport(later) entry.
Finally, this package also offers a higher-level C++ helper class tomake it easier to execute tasks on a background thread. It is alsoavailable fromlater_api.h and its public/protected interface lookslike this:
classBackgroundTask {public:BackgroundTask();virtual~BackgroundTask();// Start executing the taskvoidbegin();protected:// The task to be executed on the background thread.// Neither the R runtime nor any R data structures may be// touched from the background thread; any values that need// to be passed into or out of the Execute method must be// included as fields on the Task subclass object.virtualvoidexecute() = 0;// A short task that runs on the main R thread after the// background task has completed. It's safe to access the// R runtime and R data structures from here.virtualvoidcomplete() = 0;}
Create your own subclass, implementing a custom constructor plus theexecute andcomplete methods.
It’s critical that the code in yourexecute method not mutate any Rdata structures, call any R code, or cause any R allocations, as it willexecute in a background thread where such operations are unsafe. Youcan, however, perform such operations in the constructor (assuming youperform construction only from the main R thread) andcomplete method.Pass values between the constructor and methods using fields.
#include <Rcpp.h>#include <later_api.h>class MyTask : public later::BackgroundTask {public: MyTask(Rcpp::NumericVector vec) : inputVals(Rcpp::as<std::vector<double> >(vec)) { }protected: void execute() { double sum = 0; for (std::vector<double>::const_iterator it = inputVals.begin(); it != inputVals.end(); it++) { sum += *it; } result = sum / inputVals.size(); } void complete() { Rprintf("Result is %f\n", result); }private: std::vector<double> inputVals; double result;};To run the task,new up your subclass and callbegin(),e.g. (new MyTask(vec))->begin(). There’s no need to keep track of thepointer; the task object will delete itself when the task is complete.
// [[Rcpp::export]]void asyncMean(Rcpp::NumericVectordata) { (new MyTask(data))->begin();}
It’s not very useful to execute tasks on background threads if you can’tget access to the results back in R. Thepromises package complementslater by providing a “promise” abstraction.
About
Schedule an R function or formula to run after a specified period of time
Topics
Resources
License
Unknown and 2 other licenses found
Licenses found
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.
Contributors11
Uh oh!
There was an error while loading.Please reload this page.