Multiple periodic timers

Is there any python standard module for creating multiple periodic timers. I want to create a system that supports the creation of several periodic timers of varying periodicity, working in only one thread. The system should be able to cancel a specific timer at any given time.

Thanks in advance for any input!

+3
source share
2 answers

Check out the sched module in the Python standard library - as such, it does not support direct periodic timers, turning off "events", but it uses a standard trick to include a one-time event in a periodic timer (the called-time processing of a one-time event is simply reconfigured for the next repetition before proceeding to doing real work).

It may be convenient to define a "scheduled periodic timer" class to encapsulate key ideas:

class spt(object):

  def __init__(self, scheduler, period):
    self._sched = scheduler
    self._period = period
    self._event = None

  def start(self):
    self._event = self._sched.enter(0, 0, self._action, ())

  def _action(self):
    self._event - self._sched.enter(self._period, 0, self._action, ())
    self.act()

  def act(self):
    print "hi there"

  def cancel(self):
    self._sched.cancel(self._event)

, spt act ( ). , , __init__ , ( self.scheduler) ( , time.time time.sleep); , (, 0), 0, .

+6

1 - , , , :

import time

def example1():
    print 'Example'

class Task(object):
    def __init__(self, func, delay, args=()):
        self.args = args
        self.function = func
        self.delay = delay
        self.next_run = time.time() + self.delay

    def shouldRun(self):
        return time.time() >= self.next_run

    def run(self):
        self.function(*(self.args))
        self.next_run += self.delay
        # self.next_run = time.time() + self.delay

tasks = [Task(example1, 1)] # Run example1 every second
while True:
    for t in tasks:
        if t.shouldRun():
            t.run()
        time.sleep(0.01)

stackless - , , , .

+2

Source: https://habr.com/ru/post/1714087/


All Articles