I can run a piece of code for 5 or 10 seconds using the following code:
period <- 10 ## minimum time (in seconds) that the loop should run for tm <- Sys.time() ## starting data & time while(Sys.time() - tm < period) print(Sys.time())
The code runs just fine for 5 or 10 seconds. But when I replace the period value by 60 for it to run for a minute, the code never stops. What is wrong?
As soon as elapsed time exceeds 1 minute, the default unit changes from seconds to minutes. So you want to control the unit:
while (difftime(Sys.time(), tm, units = "secs")[] < period)
If ‘units = "auto"’, a suitable set of units is chosen, the largest possible (excluding ‘"weeks"’) in which all the absolute differences are greater than one. Subtraction of date-time objects gives an object of this class, by calling ‘difftime’ with ‘units = "auto"’.