HenrikBengtsson / startup

:wrench: R package: startup - Friendly R Startup Configuration
https://henrikbengtsson.github.io/startup/
160 stars 5 forks source link

Add on_session_exit() #106

Closed HenrikBengtsson closed 2 years ago

HenrikBengtsson commented 2 years ago

Analogously to the newly added on_session_enter(), add a startup::on_session_exit() that makes it simple to run things at the end of the current R session. It should take both R expressions and R functions as input, e.g.

startup::on_session_exit(quote({
  message("Exiting R ...")
}))

startup::on_session_exit(local({ 
  t0 <- Sys.time()
  function(...) {
    dt <- difftime(Sys.time(), t0, units = "auto")
    message(gettextf("R session exited after %.2f %s", dt, attr(dt, "units")))
  }
})

which will give:

> quit("no")
Exiting R ...
R session exited after 1.62 mins

Implementation

This should rely on reg.finalizer().

Misc.

We could also add an on_last(), that will work out of .Last(), which will only run when quit(runLast = TRUE) is called (runLast = TRUE is the default).

(*) Rename to on_first()?

HenrikBengtsson commented 2 years ago

Added on_session_exit()).