-1

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.

3
  • 1
    Short answer: you don't. taskscheduleR is for scheduling R scripts and covers everything you are currently doing in the bat file, just point 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 like RScript.exe run_my_r_script.bat, which is granted to fail. Commented Dec 5 at 9:46
  • No sure why online I read an article describing that it can be done. I will stick with scheduling an R script instead of a bat file. Thanks Commented Dec 5 at 19:15
  • If you really want to, you can trigger a bat file execution from a R script which is scheduled through 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 with schtasks.exe or Scheduled Tasks in Control Panel. Commented Dec 6 at 11:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.