From 16c556de457ca1039da194128484952ebee7c703 Mon Sep 17 00:00:00 2001 From: Sunil Mohan Adapa Date: Wed, 11 Oct 2023 16:31:15 -0700 Subject: [PATCH] glib: Add a jitter to the interval by default when scheduling tasks - When many tasks are scheduled at once, they will try to write to the database at the same time. This happens prominently in develop mode when multiple notifications are attempted to be shown. - Also other resource contention may happen. - Avoid this by adding or subtracting 5% to the provided task scheduling interval time. Tests: - Print the interval times in the schedule() method and verify that the final interval values are randomized and vary by only 5% from the provided interval. Signed-off-by: Sunil Mohan Adapa Reviewed-by: James Valleroy --- plinth/glib.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/plinth/glib.py b/plinth/glib.py index e4df1ba42..77721f713 100644 --- a/plinth/glib.py +++ b/plinth/glib.py @@ -4,6 +4,7 @@ Module to handle glib main loop and provide asynchronous utilities. """ import logging +import random import threading from plinth import dbus, network @@ -49,7 +50,8 @@ def _run(): logger.info('Glib main loop thread exited.') -def schedule(interval, method, data=None, in_thread=True, repeat=True): +def schedule(interval, method, data=None, in_thread=True, repeat=True, + add_jitter=True): """Schedule a recurring call to a method with fixed interval.""" def _runner(): @@ -74,4 +76,10 @@ def schedule(interval, method, data=None, in_thread=True, repeat=True): if cfg.develop and interval > 180: interval = 180 + if add_jitter: + # Add or subtract 5% random jitter to given interval to avoid many + # tasks running at exactly the same time (and competing for DB, disk, + # network, etc.). + interval *= 0.95 + (random.random() * 0.1) + glib.timeout_add(int(interval * 1000), _run_bare_or_thread, None)