title: What’s the principle of Timer in Python？
body: <p>The original code of Timer</p>
  <pre><code>def __init__(self, interval, function, args=None, kwargs=None):
      Thread.__init__(self)
      self.interval = interval
      self.function = function
      self.args = args if args is not None else []
      self.kwargs = kwargs if kwargs is not None else {}
      self.finished = Event()
  
  def cancel(self):
      &quot;&quot;&quot;Stop the timer if it hasn't finished yet.&quot;&quot;&quot;
      self.finished.set()
  
  def run(self):
      self.finished.wait(self.interval)
      if not self.finished.is_set():
          self.function(*self.args, **self.kwargs)
      self.finished.set() 
  </code></pre>
  <p>The  original code of Event</p>
  <pre><code>    def set(self):
      &quot;&quot;&quot;Set the internal flag to true.
  
      All threads waiting for it to become true are awakened. Threads
      that call wait() once the flag is true will not block at all.
  
      &quot;&quot;&quot;
      with self._cond:
          self._flag = True
          self._cond.notify_all()
  </code></pre>
  <p>I have some questions about fun <code>cancel()</code> and <code>run()</code>.   <code>cancel()</code> should stop the timer which means stop the thread running. However, it implements <code>cancel()</code> by <code>self.finished.set()</code>. The <code>set()</code> in <code>Event</code> is implemented by <code>self._cond.notify_all()</code>, cond is an instance of <code>Condition</code>. And when running the <code>Timer().cancel()</code>, it should notify the thread instead of stop the thread. I can't really understand these code.</p>
  <p>Also, in the function of <code>Timer().run()</code>, in this sentence &quot; <code>if not self.finished.is_set():</code> &quot;, Why does <code>self.function</code> run when <code>flag</code> is false? In my opinion， when <code>event.flag</code> is true, the thread should run, or it should wait until the flag is true.</p>