0

I want to run a function every 5 seconds. This code would work:

import threading
def notify():
    threading.Timer(5.0, notify).start()

notify()

What if the function need parameter from the previous run ? I tried this:

import threading
def notify(since):
    threading.Timer(5.0, notify(since)).start()
# initial_id is just an integer, eg 423455677
notify(initial_id)

I get error:

Traceback (most recent call last):
File "/Users/paulyu/anaconda/lib/python3.4/threading.py", line 911, in _bootstrap_inner
self.run()
File "/Users/paulyu/anaconda/lib/python3.4/threading.py", line 1177, in run
self.function(*self.args, **self.kwargs)
TypeError: notify() missing 1 required positional argument: 'since'

Howe to fix it ? Your advice is much appreciated. Thanks Paul

Paul Yu
  • 35
  • 7
  • Your input and error don't correlate. What is since supposed to be? – Padraic Cunningham May 06 '16 at 17:45
  • It's just a number I got for the notify function. For the first run, I put a number as parameter to the notify() , which the number is retrieved by other function. – Paul Yu May 06 '16 at 17:48
  • Your second example shows you called notify with no *since* parameter, what are you actually trying to achieve? – Padraic Cunningham May 06 '16 at 17:50
  • Ah, I actually put the initial id in the function to run. i.e notify(initial_id) where initial_id = 423455677 – Paul Yu May 06 '16 at 17:55
  • Your code would recurse infinitely if you called it as per your second example. What information are you using from a previous try? – Padraic Cunningham May 06 '16 at 18:06
  • Yes, I would like to make it continuous loop, run the notify function every 5 second. Would it be better to do it with a while loop ? so that I can easily initialize the routine before the while loop start. How to control the while loop every 5 second ? – Paul Yu May 06 '16 at 18:16
  • I got the answer from : http://stackoverflow.com/questions/5945533/how-to-execute-the-loop-for-specific-time Will try it first. Thanks – Paul Yu May 06 '16 at 18:20

1 Answers1

0

When you need to remember some kind of state, you generally want a class.

import threading

class Notifier:

    def __init__(self, since):
        self.since = since

    def notify(self):
        print(self.since)
        self.since += 1
        threading.Timer(2.0, self.notify).start()

Notifier(123).notify()
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Bono May 06 '16 at 19:55
  • @Bono is that better? There's not much to explain. – Alex Hall May 06 '16 at 20:04
  • @Alex Thanks! I created the class and tested it. Working very well. It's the first time I'm using a class. Start understand when and why to use it. :) – Paul Yu May 09 '16 at 14:28