Executes R code from a file in an isolated environment with comprehensive error handling, logging, and optional memory monitoring. This function is ideal for running R scripts safely with automatic error recovery.
Usage
run_local_job(
.file,
.external_val = NULL,
.job_name = NULL,
.save_when_error = T,
.save_method = c("qs2", "rds"),
.check_memory_useage = F,
.max_memory_useage = NULL,
.gc_span = 0
)
Arguments
- .file
Character. Path to the R script file to execute.
- .external_val
List. Named list of external variables to make available in the execution environment. Default is NULL.
- .job_name
Character. Optional name for the job used in logging and identification. If NULL, a timestamp-based name will be generated.
- .save_when_error
Logical. Whether to save the environment state when a fatal error occurs. Useful for debugging but requires sufficient disk space. Default is TRUE.
- .save_method
Character. Save method for error state. Either "qs2" for faster compression or "rds" for standard R serialization. Default is "qs2".
- .check_memory_useage
Logical. Whether to monitor and report memory usage in log files. Default is FALSE.
- .max_memory_useage
Numeric. Maximum memory usage in bytes. Job will be stopped if this limit is exceeded. Default is NULL (no limit).
- .gc_span
Numeric. Interval for garbage collection. If > 0, performs
gc()
every N lines of code. Default is 0 (no automatic GC).
Details
The function creates an isolated execution environment and runs the specified R script with comprehensive error handling. All execution details are logged, and in case of errors, the environment can be automatically saved for debugging.
Examples
if (FALSE) { # \dontrun{
# Basic usage - run a simple script
job_history <- run_local_job(.file = "analysis.R")
# Run script with external variables
job_history <- run_local_job(
.file = "data_processing.R",
.external_val = list(
input_data = mtcars,
threshold = 0.05,
output_dir = "results/"
),
.job_name = "mtcars_analysis"
)
# Run with memory monitoring and limits
job_history <- run_local_job(
.file = "memory_intensive.R",
.check_memory_useage = TRUE,
.max_memory_useage = 8e9, # 8GB limit
.gc_span = 10, # GC every 10 lines
.save_when_error = TRUE,
.save_method = "qs2"
)
# Check job history
print(paste("Job completed with ID:", job_history))
} # }