I am trying to run a bat file using the taskscheduler_create function from the taskscheduler R package without being sucessful. I can run the R script without problems but it crashes with a bat file. Example below:
Save this as run_my_r_script.bat in a folder (e.g., C:\R_Tasks):
@echo off
REM Change to the folder where Rscript.exe is located
REM Adjust the path to your R installation
set R_PATH="C:\Program Files\R\R-4.3.3\bin\Rscript.exe"
REM Path to your R script
set R_SCRIPT="C:\R_Tasks\my_script.R"
REM Run the R script
%R_PATH% %R_SCRIPT%
Save this as my_script.R in the same folder:
# my_script.R
# Example R script that logs the current time
log_file <- "C:/R_Tasks/log.txt"
tryCatch({
cat(sprintf("Script ran at: %s\n", Sys.time()), file = log_file, append = TRUE)
}, error = function(e) {
cat(sprintf("Error at %s: %s\n", Sys.time(), e$message), file = log_file, append = TRUE)
})
Run this in R once to create the scheduled task:
# Install if not already installed
if (!require(taskscheduleR)) install.packages("taskscheduleR")
library(taskscheduleR)
# Path to the .bat file
bat_path <- "C:/R_Tasks/run_my_r_script.bat"
# Create a daily task at 9:00 AM
taskscheduler_create(
taskname = "Run_My_R_Script",
rscript = bat_path,
schedule = "DAILY",
starttime = "09:00", #To run it, set the time a couple minutes ahead of your current time
startdate = format(Sys.Date(), "%m/%d/%Y"))
The bat file executes properly when is run manually (by double clicking on it) but it refuses to execute from taskscheduler_create() function.
taskscheduler_create()directly to you R script and if needed, pass arguments for R executable and working directory. Currently you are trying to schedule a task that executes something likeRScript.exe run_my_r_script.bat, which is granted to fail.taskscheduleR, but unless your R task is providing required input for bat, you can just skip everything related to R and schedule bat execution directly withschtasks.exeor Scheduled Tasks in Control Panel.