Dwayne
Dwayne

Reputation: 39

Python - Execute Function After Amount of Time?

What i'm trying to do is print or execute a certain string after certain amount of time, in case of this function it is 20 seconds, the problem is on the second loop, sure it waits 20 seconds on first loop, but the second loop it no longer wait, it just keeps printing.. why does this happen? and how can i solve it?

from threading import Timer
import time

startlog = time.time()

def tess():



tm = 0
while True:
    tm += 1
    print(tm)
    tess()
    time.sleep(1)

Upvotes: 0

Views: 8523

Answers (4)

Uri Goren
Uri Goren

Reputation: 13672

It sounds like you are trying to run something for 20 seconds in the background, and then execute your function.

If this is the case, you threading / multiprocessing makes more sense.

Using this decorator, your code could be rewritten as

@time_limit(20)
def will_stop_after_20_secs():
    print ("doing stuff")
    time.sleep(20)


will_stop_after_20_secs()
print ("20 seconds had passed")

Upvotes: 0

JoshuaCS
JoshuaCS

Reputation: 2624

You have to change start = time.time() to startlog = time.time() and define such variable as global or nonlocal:

def tess():
    nonlocal startlog
    ...
        startlog = time.time()

Or just wait 20 secs: time.sleep(20)

Upvotes: 0

Ankit Goyal
Ankit Goyal

Reputation: 109

You need to update your startlog variable inside loop in tess() function. You need to replace

start = time.time()

with:

startlog = time.time() 

Upvotes: 0

SimonF
SimonF

Reputation: 1885

You need to reset startlog between calls to tess that "succeed" (have passed 20 s), this code works the way you want (but is ugly because of the global variables).

import time

startlog = time.time()

def tess():
    global startlog
    if time.time() - 20 > startlog:
        print('its been 20 secs')
        startlog = time.time()


tm = 0
while True:
    tm += 1
    print(tm)
    tess()
    time.sleep(1)

Upvotes: 1

Related Questions