4

我有一个 Rscript 文件 (Main_Script.R),它每 30 分钟在 Windows 任务计划程序中作为一个调度作业运行。在里面Main_Script.R- 我有大约 13 个脚本,每 30 分钟运行一次。

我想从 R 发送电子邮件 - 每当迭代失败或拖累时。我正在使用 sendMailR 包 - 我在 SO 中看到了一篇how to send email with attachment from R in windows关于如何从 R Windows 发送 emqil 的帖子。

但我不确定 - 如何发送email automatically with the error message- 当计划的任务迭代失败或被拖走时。

我的Main_Script.R- 拥有source所有 13 个代码。

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

我的预定任务如下所示,带有日志文件

"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

更新:

当脚本遇到错误时 - 它应该触发电子邮件 - 带有错误消息和脚本名称或编号 - 以表示 13 个脚本中的哪个失败并发送到邮件 ID。

4

1 回答 1

7

这是一个包装源脚本的解决方案:

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

我的脚本是:

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

和类似的。因此:

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

所以cat用你的电子邮件发送和工作完成替换我。错误作为参数传递给处理程序,因此您可以从中获取消息。

以下是如何使用编号为示例的 13 个脚本来执行此操作,并确定哪一个出错了:

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

现在您只需要编写mailMe函数,它会获取脚本的编号和错误消息。它可能是这样的:

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)
}

请注意,您可以单独测试该mailMe功能,直到它工作为止。

于 2014-08-27T07:21:42.593 回答