FutureCake
FutureCake

Reputation: 2943

python timer and disable function

i have a function thats gets executed when the script is run. this function is called main()

timer = 0
def main():
   function2()
   function3()
   timer()

this function calls the following functions: function2, function3, and timer.

def timer():
    global timer
    while timer < 120:
        timer += 1
        timer.sleep(1)
        print timer
        if timer == 120:
            timer = 0
            function2 = false

the problem is that the timer doesn't print in the console. and function2 doesn't get disabled after 120 seconds.

what am i doing wrong? any help or suggestions would be appreciated!

Upvotes: 0

Views: 1063

Answers (2)

Kris
Kris

Reputation: 23559

I haven't looked at the logic of your code, but the first thing you need to do is disambiguate your variables, e.g.:

import time

timer_ = 0

def timer():
    global timer_
    while timer_ < 120:
        timer_ += 1
        time.sleep(1)
        print timer_
        if timer_ == 120:
            timer_ = 0
            function2 = lambda: False

def main():
    function2()
    function3()
    timer()

Upvotes: 0

L3viathan
L3viathan

Reputation: 27273

This won't work like that, a) because function2 is a local variable in timer, and b) because timer isn't run asynchronously. Also no variable called timer will be accessible inside the function, because it itself is named timer.

If you want to interrupt function2 after 120 seconds, you should just set a timer (time.time()) at the beginning of function2 and then in the loop that I assume resides in function2 check for whether the current time is more than 120 ahead of the time initially recorded upon entering the function. In that case, you can return from that function to stop it.

edit: This would be an example:

import time

def function2():
    timer = time.time()
    while True:
        if time.time() - timer > 120:
            return # time to exit from this function
        print("We are doing something!")
        time.sleep(1) # just for demonstration

def function3():
    pass # do something else

if __name__ == '__main__': # better than a function called "main"
    function2()
    function3()

Upvotes: 1

Related Questions