Search code examples
rscheduled-taskswindows-task-schedulerr-taskscheduler

R taskscheduleR not executing script


I'm trying to run a script once every minute using taskscheduleR library. I'm following the examples from the GitHub page but am running into the following problems:

  1. R says task created but the script does not execute properly (it should write data to a file in append mode - the file in question already exists)
  2. I do not see any log files - I believe they should be stored in the same location as the script being executed
  3. Deleting the task using taskscheduler_delete("rds_task") does not work

Here's my code:

taskscheduler_create(taskname = "rds_task", 
                     rscript = "./Testing_Scheduler/testing_scheduler.R",
                     schedule = "MINUTE", 
                     starttime = format(Sys.time() + 30, "%H:%M"), 
                     startdate = format(Sys.time(), "%d/%m/%Y"),
                     modifier = 1)

And the contents of testing_scheduler.R:

dat <- mtcars
data.table::fwrite(dat[1, ], "./Testing_Scheduler/testfile.txt", append = T)

To delete the task, I used:

taskscheduler_delete("rds_task")

which was unsuccessful. I ended up using the Windows Task Scheduler (my computer is in French - can't change that, sorry):

Deleting task in Windows Task Scheduler

Same result with the R add-in except that I seem to be able to delete the task that way. I have admin rights on my computer (so it should not be an access-related problem).


Solution

  • The best solution around this issue - wich works exactly as expected is to use Windows .bat file to run the script and schedule it using windows scheduler.

    The .bat file contains the commands to run R.exe using commamnd prompt (cmd) and execute the specified R code:

    @echo on
    "C:\Program Files\R\R-3.4.2\bin\x64\R.exe" CMD BATCH C:\Users\gma\Desktop\R_Task\script1.R
    

    Above are all the contents of a .bat file. The first string (in quotes) is the location where R is installed on the sytem. 'CMD' and 'BATCH' tell windows to execute it using command prompt in batch processing mode. The next string is the location of the script that you want to execute using R - provide the full file path here.

    Copy this to any text editor program and when saving, specify '.bat' as the extension.

    You can create a "basic task" in windows task scheduler that executes a program/script at required intervals or based on other triggers. The script to execute would be the .bat file that was created above. There's tons of video tutorials(like this one on youtube) on how to create such tasks so I won't go into detail here.