How to schedule an R script that uses relative paths on Linux with cronR

The cronR package provides a simple R interface to the cron scheduler.

In many cases your script depends on other files which you should reference with relative paths inside an Rstudio project with the here::here() function.

In these cases the cronR default method for adding jobs to cron produces an error:

library(cronR)

cmd <- cron_rscript("/home/rstudio/my_folder/my_script.R")
cron_add(command = cmd, frequency = 'daily', at = '18:00', id = 'test')
here() starts at /home/rstudio
Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
Calls: source -> file
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file '/home/rstudio/R/scraping_functions.R': No such file or directory
Execution halted

As we can see, cron executes the script in user’s home folder and therefore fails to find the dependent files.

We can inspect the command cmd created by the package:

cmd
[1] "/usr/lib/R/bin/Rscript '/home/rstudio/my_folder/my_script.R'  >> '/home/rstudio/my_folder/my_script.log' 2>&1"

The problem can be solved by modifying the command. First, we instruct cron to change directory to our project and then to execute the script:

cmd <- "cd '/home/rstudio/my_folder' && /usr/lib/R/bin/Rscript './my_script.R'  >> './my_script.log' 2>&1"
cron_add(command = cmd, frequency = 'daily', at = '18:00', id = 'test')
here() starts at /home/rstudio/my_folder