简体   繁体   中英

execute function every x number of secods python

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!

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()

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM