execute function every x number of secods python

2019-04-02 09:39发布

问题:

I came across this thread when I was looking for a solution, but it doesn't quite do what I need it to:

What is the best way to repeatedly execute a function every x seconds in Python?

This actually "works" (or at least the first solution does) but it doesn't allow you to do it simultaneously along with the rest of the script.

Basically, I need to execute a function like this:

    def functionName():
        print "text"

I need this to execute every, say, 100 milliseconds. But I need this while loop to be looping simultaneously:

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

How would I go about this?

Thanks!

回答1:

Shouldn't this work: http://www.pygame.org/docs/ref/time.html#pygame.time.set_timer

pygame.init()
pygame.time.set_timer(USEREVENT + 1, 100)
while True:
    for event in pygame.event.get():
        if event.type == USEREVENT + 1:
           functionName()
        if event.type == QUIT:
            pygame.quite()
            sys.exit()


回答2:

This can be done by making a thread and using the wait() function so that it prints after every wait() function :) If you need help on threads, please look at the official documentation for help or look/ask for a different question on overflow. Cheers :)



回答3:

You can probably install you function as a signal handler and use signal.setitimer. If you are on Unix, that is... Then there are threads and stuff.



标签: python pygame