1

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!

Community
  • 1
  • 1
Max Hudson
  • 9,961
  • 14
  • 57
  • 107
  • Did you take a look at [threading](http://docs.python.org/library/threading.html)? – bereal Mar 27 '12 at 17:29
  • possible duplicate of [What is the best way to repeatedly execute a function every x seconds in Python?](http://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python) – mechanical_meat Mar 27 '12 at 17:30

3 Answers3

3

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()
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

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

IT Ninja
  • 6,174
  • 10
  • 42
  • 65
0

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.

tchap
  • 1,047
  • 8
  • 10