Periodic function execution with time interval < 100 ms

537 views Asked by At

My goal is to execute a function on a periodic time interval but with a high period. The code linked below seemed very promising:
https://medium.com/greedygame-engineering/an-elegant-way-to-run-periodic-tasks-in-python-61b7c477b679. With some minor modification i ended up with this:

import threading
import time
from datetime import timedelta
from unittest.mock import Mock

WAIT_TIME_SECONDS = 0.1

class PeriodicTask(threading.Thread):
    """ Class for executing a periodic task specifying a time interval between invokations """
    def __init__(self, interval: timedelta, execute: Callable[..., None], *args, **kwargs):
        super().__init__()
        assert isinstance(interval, timedelta), "Must specifiy datetime time interval, here"
        assert not execute is None, "Must specify function which should be invoked regularly, here"

        self.daemon = False
        self.stopped = threading.Event()
        self.interval = interval
        self.execute = execute
        self.args = args
        self.kwargs = kwargs

    def stop(self):
        """ Stop periodic task """
        self.stopped.set()
        self.join()

    def run(self):
        """ Run task based on the specified interval """
        while not self.stopped.wait(self.interval.total_seconds()):
            self.execute(*self.args, **self.kwargs)

if __name__ == "__main__":
    foo = Mock()
    job = PeriodicTask(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=foo)
    job.start()

    time.sleep(1)
    job.stop()

It seems i can execute periodic tasks down to a period of approx 100ms (Intel Core i7-3770K CPU, 3.5 GHz, 16 GB RAM), before tasks hinder each other. Is there a way to optimize this code fragment so i can execute tasks periodically down to at least 10ms?

0

There are 0 answers