Interrupting readline() after a time interval in R

后端 未结 3 1563
有刺的猬
有刺的猬 2021-01-22 08:14

How to break a loop after a certain elapsed time? I have a function that collects observational data from a user. The user should have a pre-defined time limit, when the data ar

3条回答
  •  北海茫月
    2021-01-22 08:19

    i think you can use fucntion "setTimeLimit" from library base. so...

    record.events <- function(duration = 30, first.event = "a"){
        # Initial settings
        time.start <- proc.time()[3]
        events<-first.event
        stroke.time<-c(0)
    
    # Timed data collection
        while(proc.time()[3] - time.start < duration){
        temp <- tryCatch({setTimeLimit(elapsed=(time.start + duration - proc.time()[3]),
                         transient = TRUE);readline("record events...")},
                         error = function(e) { return("NULL")})
        #you need to set up back this function... (but why i dont know????)
        setTimeLimit(elapsed = Inf, transient = TRUE)
    
         events[length(events)+1] <- temp
        stroke.time[length(stroke.time)+1]<-round(proc.time()[3],3)
    }
    
    # Format recorded data for post-processing
    
    events<-data.frame(events, stroke.time) 
    return(events)
    }
    

    But setTimeLimit inst great for use in user functions.. My results is:

      events stroke.time
    1      a        0.00
    2      s     1539.12
    3      s     1539.52
    4    ass     1539.96
    5      s     1540.49
    6    asd     1540.94
    7    fed     1541.27
    8   NULL     1541.55
    

    For more info see:

    https://stackoverflow.com/a/7891479

    https://stat.ethz.ch/R-manual/R-devel/library/base/html/setTimeLimit.html

    How does setTimeLimit work in R?

    setTimeLimit fails to terminate idle call in R

提交回复
热议问题