How to run a background timer in Python

前端 未结 1 1759
一个人的身影
一个人的身影 2020-12-12 02:34

I\'m currently making a math game where the user has 60 seconds to answer as many questions as possible. As of now, I have everything working except for the timer which shou

相关标签:
1条回答
  • 2020-12-12 03:10

    Use time.time(), it returns the epoch time (that is, the number of seconds since January 1, 1970 UNIX Time). You can compare it to a start time to get the number of seconds:

    start = time.time()
    while time.time() - start < 60:
        # stuff
    

    You can have a timer pull you out of your code at any point (even if the user is inputting info) with signals but it is a little more complicated. One way is to use the signal library:

    import signal
    def timeout_handler(signal, frame):
        raise Exception('Time is up!')
    signal.signal(signal.SIGALRM, timeout_handler)
    

    this defines a function that raises an exception and is called when the timeout occurs. Now you can put your while loop in a try catch block and set the timer:

    signal.alarm.timeout(60)
    try:
        while lives > 0
            # stuff
    except:
        # print score
    
    0 讨论(0)
提交回复
热议问题