import tornado.ioloop def task(): print("Hello, world!") periodic_task = tornado.ioloop.PeriodicCallback(task, 1000) # execute task every 1 second periodic_task.start() tornado.ioloop.IOLoop.current().start() # start the event loop
import tornado.ioloop class Sensor: def __init__(self, name): self.name = name self.value = 0 def read(self): # read sensor value from hardware and save it self.value += 1 print(f"{self.name}: {self.value}") s1 = Sensor("Sensor 1") s2 = Sensor("Sensor 2") periodic_task = tornado.ioloop.PeriodicCallback(lambda: s1.read(), 500) # read s1 every 0.5 seconds periodic_task.start() tornado.ioloop.PeriodicCallback(lambda: s2.read(), 1000).start() # read s2 every 1 second tornado.ioloop.IOLoop.current().start() # start the event loopThis example demonstrates how to use `PeriodicCallback` to periodically read values from multiple sensors. The `Sensor` class represents a hardware sensor that provides its value when read. The periodic tasks are defined using lambda functions that call the `read()` method of the sensors. Sensor 1 is read every 0.5 seconds, and Sensor 2 is read every 1 second. Both of these examples use the `tornado.ioloop` package library, which is part of the Python Tornado framework.