JimGrange
JimGrange

Reputation: 272

CRON not executing R script file

I am trying to automate running of a script (test.R) in R stored on a desktop folder (cron_test). I am using CRON in my mac terminal. The example R script generates random numbers, plots them, and saves them to a PDF:

setwd("~/Desktop/cron_test")

pdf("example_plot.pdf", width = 8, height = 8)
plot(rnorm(100))
dev.off()

My CRON code attempts to call this every minute, but nothing appears in the folder:

* * * * * Rscript /Users/username/Desktop/cron_test/test.R

Nothing is being generated. I have tried the following:

I am receiving mail to state that the CRON task has run, but no output is appearing in my cron_test folder.

Upvotes: 1

Views: 782

Answers (1)

Chris Edsall
Chris Edsall

Reputation: 61

Does the mail say

/bin/sh: Rscript: command not found

?

If so, try using the full path to Rscript. You can find this from the terminal with

$ which Rscript

The reason for this is that the environment you get in a cron session is much smaller compared to that in an interactive terminal. You can examine this by comparing the outputs of

$ /usr/bin/env > env-interactive

and the cron job

* * * * * /usr/bin/env > env-cron

We can see these are quite different by counting the number of lines in each file.

$ wc -l env-{interactive,cron}
      20 env-interactive
       8 env-cron

In particular the shell executable search path ($PATH) in the cron job is much shorter

$ grep PATH env-{interactive,cron}
env-interactive:PATH=/Users/hpcchris/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/munki:/opt/X11/bin:/Applications/Wireshark.app/Contents/MacOS:/Users/hpcchris/bin
env-cron:PATH=/usr/bin:/bin

(Using the full path /usr/local/bin/Rscript worked for me with R on my macos High Sierra laptop and produced the plot.)

Upvotes: 2

Related Questions