如何正确实现R语言中的定时等待以规避每小时下载限制
I once saw an R example for a 10-second code wait:
period <- 10 ## minimum time (in seconds) that the loop should run for tm <- Sys.time() ## starting date & time while (difftime(Sys.time(), tm, units = "secs")[[1]] < period)Now I need to pause my program for one hour because of hourly download limits. I tried writing this code:
period <- 60 tm <- Sys.time() ## starting date & time while (difftime(Sys.time(), tm, units = "minutes")[[1]] < period)But I don't think this approach is correct. Can anyone help me find a proper implementation method?
Hey there, let's sort this out for you!
First off, your current loop approach isn't ideal—it's what's called a "busy wait," meaning it's constantly checking the time and eating up unnecessary CPU resources. R actually has a built-in function made exactly for pausing execution cleanly: Sys.sleep().
The Simple, Efficient Solution
If all you need is to pause the program for one hour, just use this one line:
# Pause for 1 full hour (3600 seconds total) Sys.sleep(3600)
Sys.sleep() takes a number of seconds as its argument, so we calculate 60 minutes × 60 seconds = 3600. This puts your program to sleep without wasting any processing power while waiting.
Why Your Original Approach Falls Short
Right now, your while loop doesn't have any code inside it—without a body (like a NULL or small sleep), it could even run infinitely. Even if you added something, the loop would still be spinning non-stop checking the time, which is totally unnecessary when Sys.sleep() handles this task perfectly.
If You Must Use a Time-Check Loop (Not Recommended)
If you have a specific reason to use a time-based loop (like needing to run small tasks while waiting), at least add a short sleep inside the loop to cut down on CPU usage:
period <- 3600 # 1 hour in seconds tm <- Sys.time() while (difftime(Sys.time(), tm, units = "secs")[[1]] < period) { Sys.sleep(1) # Wait 1 second between time checks to save CPU }
But again, the Sys.sleep(3600) method is the standard best practice here.
内容的提问来源于stack exchange,提问作者Tom

