pankaj pankaj - 3 months ago 11
R Question

Placing different values for Sys.sleep in a loop , multiple time values

I have a code and i am using a loop inside it , now i want this loop to be stopped for a short time interval after it completes one query. But when this loop executes the next query i want it to be stopped for different time interval.
For eg
After 1st query - 10sec
After 2nd query - 15sec and so on..

Following is the loop

for (i in 1:nrow(uniquemail)) {
k <- 2
test3 <- subset(finaltest, finaltest$Email == uniquemail[i,1])
for (j in 1:nrow(test3)) {

uniquemail[i,k] <- test3[j,2]
uniquemail[i,k+1] <- as.character(test3[j,3])
uniquemail[i,k+2] <- as.numeric(test3[j,4])
uniquemail[i,k+3] <- as.numeric(test3[j,5])

k <- k+4

print(paste(i,j,k))
}
}


Is there any way i could get this done . I used
Sys.sleep
but don't know how to use it for my motive above .

Answer

In case you want to create a sleep-loop for each iteration, and start the timing for sleeping duration before your actions, and increase the sleep with 5 seconds per loop you can use this code: See below:

for (j in 1:3) {
tm <- proc.time() #take timing before your action

#do your things here
#
#

tmdiff <-(5 * j) - (proc.time()[3] - tm[3]) #you want to wait 5 seconds the first time,
#10 sec the second time, 15 sec the third time etc..

if (tmdiff > 0) {
  #depending of how long your "thing" took,
  print(paste("sleep for", tmdiff, "seconds"))#you are taking the difference from the start to end of "actions" and sleeping for that time
  Sys.sleep(tmdiff)
  }
}

if you want to start the sleeping duration after your actions:

for (j in 1:3) {    
    #do your things here
    #
    #  
      tmsleep<-(5 * j) #you want to wait 5 seconds the first time,
                       #10 sec the second time, 15 sec the third time etc..
      print(paste("sleep for", tmsleep, "seconds"))
      Sys.sleep(tmsleep)
    }
  }

Since we don't have any further information about your problem (nor a reproducible code), I assume your running into problems with overloading some type of API and/or webscraping. If so, I would rather sample my sleep time from a selected range of values such as:

tmsleep<-sample(5:15,1)
Sys.sleep(tmsleep)

i.e. sleep for a value between 5 to 15 seconds. Also if you want to have a predictable sleep time you can use set.seed(j), where j is the looping variable:

set.seed(j)
tmsleep<-sample(5:15,1)
Sys.sleep(tmsleep)
Comments