https://github.com/moodymudskipper/recycle
Set Hook on Garbage Collection
https://github.com/moodymudskipper/recycle
Last synced: 8 days ago
JSON representation
Set Hook on Garbage Collection
- Host: GitHub
- URL: https://github.com/moodymudskipper/recycle
- Owner: moodymudskipper
- License: other
- Created: 2024-02-21T14:05:42.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-03-30T21:50:13.000Z (about 1 year ago)
- Last Synced: 2025-04-12T20:52:17.366Z (8 days ago)
- Language: R
- Size: 52.7 KB
- Stars: 9
- Watchers: 2
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.Rmd
- License: LICENSE
Awesome Lists containing this project
- jimsghstars - moodymudskipper/recycle - Set Hook on Garbage Collection (R)
README
---
output: github_document
---```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
```[](https://lifecycle.r-lib.org/articles/stages.html#experimental)
# recycle
{recycle} provides a way to set a hook on garbage collection. This is useful
for instance if you want to run a R process periodically. Use cases might be:* Notifications
* Logs
* Diagnostics
* UpdatesYou can't pick when garbage collection occurs but it is frequent, so
the next best thing is to pick a minimum delta between calls to the hook, and
this is what we do (1 sec by default).## Installation
Install with:
``` r
remotes::install_github("moodymudskipper/recycle")
```## Example
```{r, eval = FALSE}
library(recycle)
log_mem <- function() message(sprintf("This R session currently takes %s", capture.output(pryr::mem_used())))# set the hook and triggers it a first time, use a 1 sec delta by default
recycle(log = new_cycle(log_mem))
#> This R session currently takes 48.8 MB# doesn't trigger the hook, too soon!
invisible(gc())Sys.sleep(2)
some_object <- sample(1e6)
# triggers the hook again
invisible(gc())
#> This R session currently takes 53.1 MB
```We can also run the code in the background in another session by using `new_cycle_bg()`.
Let's have a purposeless progress bar widget fill up on garbage collection.
Run the following example in your session and you should see that your session
is still active while the progress bar is running. Note how the previous hook
is still active.```{r, eval = FALSE}
fill_pb <- function() {
pb <- tcltk::tkProgressBar()
for(i in 1:100) {
Sys.sleep(0.05)
tcltk::setTkProgressBar(pb, i/100, sprintf("test (%d%% done)", i))
}
}
recycle::recycle(pb = new_cycle_bg(fill_pb))
#> This R session currently takes 53.5 MB
x <- 1 # the progress bar is still going on
x
```We can remove a hook by setting it o `NULL`, e.g. `recycle(log = NULL)`, or
remove all hooks altogether by calling `uncycle()`## dependencies
The package has few dependencies, including recursive dependencies these are :
* rlang
* callr
* processx
* ps
* R6