Sending email from R - when scheduled script crashes on Windows

I have an Rscript file (Main_Script.R) that runs as a scheduled task in Windows Task Scheduler every 30 minutes. Inside Main_Script.R

- I have about 13 scripts that run every 30 minutes.

I wanted to send an E-mail from R - whenever the iteration fails or fails. I am using the sendMailR package - and I saw a post on SO how to send email with attachment from R in windows

- on how to send emqil from R Windows.

But I'm not sure how to submit email automatically with the error message

when the scheduled task iteration fails or is reversed.

My Main_Script.R

- has source

all 13 codes.

source(paste(rootAddress,"Scripts/Part1.R",sep =''))
source(paste(rootAddress,"Scripts/Part2.R",sep =''))
:
:
:
:
source(paste(rootAddress,"Scripts/Part13.R",sep =''))

      

My Sheduled task looks like below with log file

"D:\xxx\R-3.0.2\bin\x64\Rscript.exe" "D:\xx\Batch_Processing\Batch_Processing_Run\Scripts\Main_Test.R" >> "D:\XXX\Batch_Processing\Batch_Processing_Run\error.txt" 2>&1

      

Update:

When a script error encounters an error - it should fire up an email - named erorr meassge and a script name or number - to indicate which of the 13 scripts failed and sent the mail id.

+3


source to share


1 answer


Here is a solution that wraps your script sources:

tryCatch({
source("fail1.R")
source("fail2.R")
source("fail3.R")
},
         error=function(e){cat("send email with error ",e$message,"\n")})

      

My scripts:

if(x==1){stop("Fail One!")}

      

etc. Hence:

> x=22
> source("doall.R")
> x=2
> source("doall.R")
send email with error  Fail Two! 

      



So, replace mine with cat

sending email and done work. The error is passed as an argument to the handler so that you can receive a message from it.

Here's how to do it with 13 scripts numbered like your example and determine which one went wrong:

for(i in 1:13){
 try( {
      source(paste(rootAddress,"Scripts/Part",i,".R",sep =''))
      },
      error = function(e){mailMe(i, e$message)}
    )
}

      

Now you just need to write a function mailMe

that gets the script number and error message. It could be something like this:

mailMe = function(i, message){
  subject=paste("Error in script ",i)
  body = paste("Error was ",message," in script ",i)
  someSendmailRfunction(to="me@my.come", subject=subject,body=body, etc=etc)
}

      

Please note that you can test the function mailMe

separately until it works.

+6


source







All Articles