Prompt user without waiting

138 views Asked by At

I have a long running process, coded in "R". I would like to continue running it in RStudio, I don't want to use batch mode.

I would like to allow the user to gracefully terminate the long running process, for example by pressing the escape key. If the user doesn't press anything, the process continues, without waiting.

I have read other StackOverflow posts, perhaps I need to prompt the user using scan/readline on a different thread. That way, the main execution thread isn't blocked.

Isn't there a simpler way?

Thank you for any pointers/suggestions.

Richard Rogers


Further comments:

I've made a few mistakes:

  1. I didn't realize that pressing escape in RStudio while the code is running halts execution.
  2. I can't seem to determine where execution ends when I press escape.
  3. Maybe I can use a simpler question.

Here is a simple function:

ProcessData <- function()
{
    Continue <- TRUE
    Iteration <- 1

    TestData <- vector(mode = "integer", length = 100000)

    while (Continue)
    {
        writeLines(sprintf("Processing iteration %d, Current time is %s", Iteration, Sys.time()))
        process.events()

        TestData <- round(runif(100000, min = 1, max = 10))
        # Continue <- PromptUser()

        Iteration <- Iteration + 1
    }

    writeLines("Processing ending.")
    head(TestData)
}

If I press escape while the loop is running, the writeLines and head calls don't get executed. How can I ensure that they do?

Thank you again,

Richard

1

There are 1 answers

0
Karsten W. On

I know this is an old question, but since I had a similar context (long-running task), here is what I came up with:

long_computation <- function() for(i in 1:10) Sys.sleep(1) 
exit_gracefully <- function() cat("Saving results so far...\n")
tryCatch(
    long_computation(),  
    finally = exit_gracefully()
)

If we press escape during the computation, no error condition seems to be thrown; however the finally part of tryCatch gets executed. This allows us to clean up, close connections etc.