-2

I have a loop that collects data from a website every minute (while(TRUE){ xyz }). It is crucial to me that that process is running continuous. I was wondering if there is a way to check if the loop is still running? Also, when it has stopped running, I'd like an email/sms.

What I can do is write Sys.time() at the end of each loop to a file, which then can be picked up with the other independent R script (ran on a different machine), which compares the timestamp with the current time. If the timestamp is >3 minutes old, it means the last 2 loops were not performed, and sends the email/sms.

Would this be the easiest way? Or am I missing something?

Blundering Ecologist
  • 1,199
  • 2
  • 14
  • 38
Luc
  • 899
  • 11
  • 26

1 Answers1

0

If I understand your question well, something like that might do the job

library(sendmailR)
## Set a counter increment
counter <- 0
## Initialising the text file
file_name <- "file_out.txt"

## Mail details
from <- "you@account.com"
to <- "recipient@account.com"
subject <- "Email Subject"
body <- "Email body."
mailControl=list(smtpServer="serverinfo")
attachmentPath <- file_name
attachmentName <- file_name

## Loop example
while(class(counter) == "numeric") {
    ## Pausing the loop for the example
    Sys.sleep(1)
    ## Updating the time
    new_time <- Sys.time()
    ## Printing the time out of R
    write(as.character(new_time), file = file_name, append = TRUE)

    ## Check the last time
    old_time <- scan(file_name, sep="\n", what="char(0)", skip = counter)

    ## Incrementing the counter
    counter <- counter + 1

    ## Compare both times
    time_difference <- as.POSIXlt(new_time)-as.POSIXlt(old_time)

    ## time difference is too long
    if(time_difference > 3) {
        counter <- FALSE
    }

    ## Exiting the loop for the example
    if(counter > 5) {
        counter <- FALSE
    }
}

## Send the email if the loop was exited on a FALSE counter
if(class(counter) == "logical" && counter == FALSE) {
    attachmentObject <- mime_part(x = attachmentPath, name = attachmentName)
    bodyWithAttachment <- list(body, attachmentObject)
    sendmail(from = from, to = to, subject = subject, msg = bodyWithAttachment, control = mailControl)
}

More details on printing the Sys.time() in a file, you can follow the procedure here: Write lines of text to a file in R

More details on sending emails at the end of the loop: How to send an email with attachment from R in windows.

Thomas Guillerme
  • 1,747
  • 4
  • 16
  • 23