

.. _sphx_glr_gallery_event_handling_timers.py:


======
Timers
======

Simple example of using general timer objects. This is used to update
the time placed in the title of the figure.




.. image:: /gallery/event_handling/images/sphx_glr_timers_001.png
    :align: center





.. code-block:: python

    import matplotlib.pyplot as plt
    import numpy as np
    from datetime import datetime


    def update_title(axes):
        axes.set_title(datetime.now())
        axes.figure.canvas.draw()

    fig, ax = plt.subplots()

    x = np.linspace(-3, 3)
    ax.plot(x, x ** 2)

    # Create a new timer object. Set the interval to 100 milliseconds
    # (1000 is default) and tell the timer what function should be called.
    timer = fig.canvas.new_timer(interval=100)
    timer.add_callback(update_title, ax)
    timer.start()

    # Or could start the timer on first figure draw
    #def start_timer(evt):
    #    timer.start()
    #    fig.canvas.mpl_disconnect(drawid)
    #drawid = fig.canvas.mpl_connect('draw_event', start_timer)

    plt.show()

**Total running time of the script:** ( 0 minutes  0.056 seconds)



.. only :: html

 .. container:: sphx-glr-footer


  .. container:: sphx-glr-download

     :download:`Download Python source code: timers.py <timers.py>`



  .. container:: sphx-glr-download

     :download:`Download Jupyter notebook: timers.ipynb <timers.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.readthedocs.io>`_
