How can I run my R script with taskscheduleR?

1k Views Asked by At

Using the taskscheduleR library I am trying to run a simple R script that creates a histogram of randomly distributed numbers.The script was set to run every 5 minutes. So I left R Studio open, expecting to see the histogram shape change every 5 minutes, but the scheduler never ran.

Please see the code for the'script' and'scheduler' below:

histogram.R script

rawData <- rnorm(10000)
hist(rawData,
     col = "lightblue",
     main = "Histogram of Random Data")

The code for the task scheduler is as follows:

library(taskscheduleR)

hscript <- "C:/Users/IFEANYI/Documents/RData/histogram.R"

run_script <- taskscheduler_create(
  taskname = "Histogram",
  rscript = hscript,
  schedule = "MINUTE",
  starttime = format(Sys.time() + 60, "%H:%M"),
  modifier = 5
)

Any suggestion?

1

There are 1 best solutions below

0
On

There are several reasons, why the script does not work, e.g. a wrong path name. It can also be that the task runs, but one does not see anything (or only a shortly opening window), as the script runs as a separate background R task, not in the R console where the task was started. The task is installed in the system task scheduler, so it continues even after RStudio is closed.

One idea to see something is to redirect the histogram to a file, like follows:

## create a random file name in the script's working directory
file <- paste0(tempfile(tmpdir="d:/temp/taskscheduleR"), ".png")
png(file)

rawData <- rnorm(10000)
hist(rawData,
     col = "lightblue",
     main = "Histogram of Random Data")
dev.off()

Here I created an own temporary folder and let the filename generate at random.

Important: This creates a task in the task scheduler of the operating system. Don't forget to remove the task at the end with taskscheduler_stop("histogram") in R or directly in the Windows task scheduler.

More about this can be found at the github page of the package: https://github.com/bnosac/taskscheduleR