Computers are great at doing repetitive things a lot, so why deprive them of doing what they do best by manually re-running the same code every night? Here we create a simple bash script to execute an R script and define a *.plist so that launchd, under OSX, can run it periodically. The *.plist code given here is configured to run a shell script every day at 8:00 PM.
R script
setwd('~/') xBar <- mean(c(1,2,1,21,2,3,2)) write.csv(xBar,'rOutput.csv')
Save code as rCode.R to the ~/
directory.
Bash shell script
/usr/bin/Rscript ~/rCode.R
Save code as rShellScript.sh file to the ~/
directory.
Execute chmod +x rShellScript.sh
in the terminal to make this file runnable.
*.plist file
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.rTask</string> <key>ProgramArguments</key> <array> <string>/Path/to/shell/script/rShellScript.sh</string> </array> <key>StartCalendarInterval</key> <dict> <key>Hour</key> <integer>20</integer> <key>Minute</key> <integer>00</integer> </dict> </dict> </plist>
Save code as com.rTask.plist file under path ~/Library/LaunchAgents
.
Run the command launchctl load ~/Library/LaunchAgents/com.rTask.plist
.
In this way, we should now be able to periodically run an R script automatically. Fun, huh? For a more lengthy description of how to do this and how it all works see the Creating Launch Daemons and Agents section of the Daemons and Services Programming Guide under the Mac Developer Library at the developer.apple.com website.