rrstudiowindows-task-schedulerrenv

Task scheduler batch file not executing R script with renv


Created a simple project using Rstudio and included renv. It simply creates txt file in project directory.

enter image description here

created batch file:

CALL "C:\Program Files\R\R-4.3.2\bin\Rscript.exe" -e "renv::load('C:/Users/username/R/ProjectFolder'); source('C:/Users/username/R/Test1/Test1.R')"> "C:/Users/username/R/Test1/Output.log" 2>&1   
exit

If I double click on batch file - works fine.

But if I use task scheduler to run batch file it gives me an error:

Error in loadNamespace(x) : there is no package called 'renv'
Calls: loadNamespace -> withRestarts -> withOneRestart -> doWithOneRestart
Execution halted

Seems like it does not activate renv.

Task scheduler snip:

enter image description here


Solution

  • renv functionality requires that the R process start in the project directory, calling Rscript -e /some/path/to/file.R does not accomplish that. In Task Scheduler, per https://serverfault.com/q/609651/316496, jobs tend to start in %Windir%\System32\, not your project directory.

    Modify your script so that it first changes to the appropriate directory and then calls Rscript, perhaps

    CD C:\Users\username\R\ProjectFolder
    CALL "C:\Program Files\R\R-4.3.2\bin\Rscript.exe" -e "renv::load('C:/Users/username/R/ProjectFolder'); source('C:/Users/username/R/Test1/Test1.R')"> "C:/Users/username/R/Test1/Output.log" 2>&1   
    exit
    

    (I'm not certain if R\ProjectFolder\ or R\Test1\ is the project with .Rprofile and renv's stuff, adjust as appropriate.