4
from threading import Timer

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start()

This code only fires the timer once.

How can I make the timer run forever?

Thanks,

updated

this is right :

import time,sys

def hello():
    while True:
        print "Hello, Word!"
        sys.stdout.flush()
        time.sleep(2.0)
hello()

and this:

from threading import Timer

def hello():
    print "hello, world"
    sys.stdout.flush()
    t = Timer(2.0, hello)
    t.start()

t = Timer(2.0, hello)
t.start()
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
zjm1126
  • 63,397
  • 81
  • 173
  • 221

5 Answers5

9

A threading.Timer executes a function once. That function can "run forever" if you wish, for example:

import time

def hello():
    while True:
        print "Hello, Word!"
        time.sleep(30.0)

Using multiple Timer instances would consume substantial resources with no real added value. If you want to be non-invasive to the function you're repeating every 30 seconds, a simple way would be:

import time

def makerepeater(delay, fun, *a, **k):
    def wrapper(*a, **k):
        while True:
            fun(*a, **k)
            time.sleep(delay)
    return wrapper

and then schedule makerepeater(30, hello) instead of hello.

For more sophisticated operations, I recommend standard library module sched.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • but i can't see print anything – zjm1126 Apr 24 '10 at 02:42
  • hi alex, and did you know how to make this in a therad ..thanks – zjm1126 Apr 24 '10 at 03:30
  • `print` from a thread (assuming that's what you mean by "therad") may not be a great idea -- the `logging` module is guaranteed to be thread-safe, `print` isn't. Anyway, if you schedule the result of `makerepeater` with `Timer`, it will of course (try to) run in its own thread. – Alex Martelli Apr 24 '10 at 04:42
9

Just restart (or recreate) the timer within the function:

#!/usr/bin/python
from threading import Timer

def hello():
    print "hello, world"
    t = Timer(2.0, hello)
    t.start()

t = Timer(2.0, hello)
t.start()
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • I know, right? It seems every answer to this question was downvoted without any explanation. – zneak Apr 24 '10 at 02:06
  • Author or someone else seems to be trolling :/ – user202459 Apr 24 '10 at 02:08
  • this does not work for me: `raise RuntimeError("thread already started")` – daniel Nov 28 '13 at 16:06
  • 1
    @zoodbergi, not sure what you're doing wrong, that works fine in 2.7.3 and 3.2.3 (once parentheses are added to the `print`). No exceptions are raised. – paxdiablo Jan 14 '14 at 05:28
  • It doesn't seem possible to restart _an existing_ `Timer`, however rebinding your identifier `t` to a _new_ `Timer` then starting that _is_ possible, which is what this example shows. I assume @zoidbergi that you did not create a new timer, hence the error. (As per docs `Timer` is a subclass of `Thread`.) – boycy Feb 06 '14 at 19:50
1

from threading import Timer it depends on which part you want to run for ever, if it's creating a new thread let's say every 10 seconds you can do the following from threading import Timer

import time
def hello():
    print "hello, world"

while True: #Runs the code forever over and over again, called a loop
    time.sleep(10)#Make it sleep 10 seconds, as to not create too many threads
    t = Timer(30.0, hello)
    t.start()

if it's the hello world you want to run forever you can do the following:

from threading import Timer

def hello():
    while True: # Runs this part forever
        print "hello, world"

t = Timer(30.0, hello)
t.start()

Search up loops in python to get more info on this

user202459
  • 631
  • 1
  • 6
  • 10
1

You can create a repeating timer by subclassing the threading.Timer class and overriding the run method to use a loop.

from threading import Timer

class RepeatingTimer(Timer):
    
    def run(self):
        """Start the timer (overrides Thread.run)."""
        while True:
            # Wait for the set flag or timeout.
            self.finished.wait(timeout=self.interval)
            if not self.finished.is_set():
                self.function(*self.args, **self.kwargs)
            else:
                # Do not need to set the finished event flag since this loop
                # will only end if the flag is set.
                break

See the Timer class implementation as well as the Event documentation for additional information.

nalyd88
  • 4,940
  • 8
  • 35
  • 51
0

This is my code for this problem:

import time
from  threading import Timer

class pTimer():
    def __init__(self,interval,handlerFunction,*arguments):
        self.interval=interval
        self.handlerFunction=handlerFunction
        self.arguments=arguments
        self.running=False
        self.timer=Timer(self.interval,self.run,arguments)

    def start(self):
        self.running=True
        self.timer.start()
        pass

    def stop(self):
        self.running=False
        pass

    def run(self,*arguments):
        while self.running:
           self.handlerFunction(arguments)
           time.sleep(self.interval)

Another script page:

def doIt(arguments):
    #what do you do
    for argument in arguments:
        print(argument)

mypTimer=pTimer(2,doIt,"argu 1","argu 2",5)

mypTimer.start()
samet kaya
  • 105
  • 3