-2

Hello I just make this script loop, but now it loops indefinitely, I would like to make the loop every 5 seconds for example, I run the script and wait 5 seconds and run again. This is the code that i have right now.

import gdown

def test():
    url = 'https://drive.google.com/uc?id=1RUySVmR2ASrnNf3XV4sdIpKD4QbUlQL8A'
    output = 'spam.txt'
    gdown.download(url, output, quiet=False)

while True:
    test()
Error Hunter
  • 1,354
  • 3
  • 13
  • 35
Miguel
  • 35
  • 4
  • what about time.sleep(*time*)? – Eden Moshe Dec 23 '20 at 16:19
  • Does this answer your question? [How do I get my Python program to sleep for 50 milliseconds?](https://stackoverflow.com/questions/377454/how-do-i-get-my-python-program-to-sleep-for-50-milliseconds) – Georgy Dec 24 '20 at 14:25
  • @Miguel the answer you have accepted is quite inefficient, consider accepting any one of the other answers. – Jarvis Dec 25 '20 at 13:16

3 Answers3

4

I think the easiest way is to simply add a pause.

import gdown
from time import sleep

def test():
    url = 'https://drive.google.com/uc?id=1RUySVmR2ASrnNf3XV4sdIpKD4QbUlQL8A'
    output = 'spam.txt'
    gdown.download(url, output, quiet=False)

while True:
    test()
    sleep(5)
FailureGod
  • 332
  • 1
  • 12
3

Just sleep for 5 seconds then:

import time

while True:
    test()
    time.sleep(5)
Jarvis
  • 8,494
  • 3
  • 27
  • 58
-1
import time

def test():
    print("running code")

start = time.time()

while 1:
    if time.time()-start >= 5:
        test()
        start = time.time()

The 5 is for the seconds. This way means that the rest of your program does not have to wait for five seconds, which maybe more useful.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Note that if you do this method you will use a bunch of cpu power just spinning through the loop doing nothing. The other solutions that use `time.sleep` keep the CPU usage to a minimum. – FailureGod Dec 23 '20 at 19:16
  • Only use this method if you want only that chunck of code to run every second and the rest of the program to carry on as normal – Mofie The greate Jan 29 '21 at 18:13