changeset 373:847996394688

Scheduling a task for periodic execution
author Sebastien Jodogne <s.jodogne@gmail.com>
date Sun, 05 Apr 2020 10:25:36 +0200
parents 8f7e9ebf7c96
children f5bbdabb04d9
files Sphinx/source/plugins/python.rst
diffstat 1 files changed, 36 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/Sphinx/source/plugins/python.rst	Thu Apr 02 08:40:20 2020 +0200
+++ b/Sphinx/source/plugins/python.rst	Sun Apr 05 10:25:36 2020 +0200
@@ -380,7 +380,42 @@
                   print('  - Method %s(): %s' % (subname, inspect.getdoc(subobj)))
           print('')
 
-  
+
+.. _python-scheduler:
+
+Scheduling a task for periodic execution
+........................................
+
+.. highlight:: python
+
+The following Python script will periodically (every second) run the
+function ``Hello()`` thanks to the ``threading`` module::
+
+  import orthanc
+  import threading
+
+  TIMER = None
+
+  def Hello():
+      global TIMER
+      TIMER = None
+      orthanc.LogWarning("In Hello()")
+      # Do stuff...
+      TIMER = threading.Timer(1, Hello)  # Re-schedule after 1 second
+      TIMER.start()
+
+  def OnChange(changeType, level, resource):
+      if changeType == orthanc.ChangeType.ORTHANC_STARTED:
+          orthanc.LogWarning("Starting the scheduler")
+          Hello()
+
+      elif changeType == orthanc.ChangeType.ORTHANC_STOPPED:
+          if TIMER != None:
+              orthanc.LogWarning("Stopping the scheduler")
+              TIMER.cancel()
+
+  orthanc.RegisterOnChangeCallback(OnChange)
+