Steven D'Aprano wrote:
On Wed, 23 Jun 2010 10:29:11 pm Nethirlon . wrote:
Hello everyone,

I'm new at programming with python and have a question about how I
can solve my problem the correct way. Please forgive my grammar,
English is not my primary language.

I'm looking for a way to repeat my function every 30 seconds.


The easiest way is to just run forever, and stop when the user interrupts it with ctrl-D (or ctrl-Z on Windows):

# untested
def call_again(n, func, *args):
    """call func(*args) every n seconds until ctrl-D"""
    import time
    try:
        while 1:
            start = time.time()
            func(*args)
            time.sleep(n - (time.time()-start))
    except KeyboardInterrupt:
        pass

Of course, that wastes a lot of time sleeping.

But "wasting time" was the stated goal. If there's nothing else the application needs to do, sleep() is perfect. I'm sure you know, but maybe some others don't: sleep() uses essentially no CPU time, so the other applications on the system get all the performance.

As an alternative, you need to look at threads. That's a big topic, you probably need to read a How To or three on threads.

Only if there's other things that need doing in the same application.


DaveA
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to