I want to run a code that runs a function with a parameter (eg. greet(h)) every 5 seconds. I tried using threading but it doesn’t work. It executes just once. See the code below and the errors:
import threading
oh_hi = "Hi guys"
def greeting(hello):
print "%s" % hello
threading.Timer(1, greeting(oh_hi)).start()
Error shown below:
> >>> ================================ RESTART
> ================================
> >>> Hi guys
> >>> Exception in thread Thread-1: Traceback (most recent call last):
> File "C:\Python27\lib\threading.py",
> line 530, in __bootstrap_inner
> self.run() File "C:\Python27\lib\threading.py", line
> 734, in run
> self.function(*self.args, **self.kwargs) TypeError: 'NoneType' object is not callable
Kindly assist.
Thanks
As others have pointed out, the error is because you’re not passing the proper arguments to the
threading.Timer()method. Correcting that will run your function, once, after 5 seconds. There are a number of ways to get it to repeat.An object-oriented approach would be to derive a new
threading.Threadsubclass. While it would be possible to create one that does specifically what you want — namelyprint "%s" % hello— it’s only slightly more difficult to craft a more generic, parameterized, subclass that will call a function passed to it during its instantiation (just likethreading.Timer()). This is illustrated below:Output:
Besides overriding the base
threading.Threadclass’s__init__()andrun()methods, astop()method was added to allow the thread to be terminated when desired. I also simplified theprint "%s" % helloin yourgreeting()function to justprint hello.