From 6d1de0b6c94732e8b86dce098f5a9bf381cecd78 Mon Sep 17 00:00:00 2001 From: woodser Date: Thu, 25 Apr 2024 16:45:49 -0400 Subject: [PATCH] TaskLooper does not target fixed period by default --- src/main/java/monero/common/TaskLooper.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/java/monero/common/TaskLooper.java b/src/main/java/monero/common/TaskLooper.java index 4f21eb56..0afd82f8 100644 --- a/src/main/java/monero/common/TaskLooper.java +++ b/src/main/java/monero/common/TaskLooper.java @@ -29,7 +29,7 @@ public TaskLooper(Runnable task) { public Runnable getTask() { return task; } - + /** * Start the task loop. * @@ -37,6 +37,18 @@ public Runnable getTask() { * @return this instance for chaining */ public synchronized TaskLooper start(long periodInMs) { + start(periodInMs, false); + return this; + } + + /** + * Start the task loop. + * + * @param periodInMs the loop period in milliseconds + * @param targetFixedPeriod specifies if the task should target a fixed period by accounting for run time + * @return this instance for chaining + */ + public synchronized TaskLooper start(long periodInMs, boolean targetFixedPeriod) { synchronized (this) { setPeriodInMs(periodInMs); if (isStarted) return this; @@ -55,9 +67,9 @@ public void run() { long startTime = System.currentTimeMillis(); task.run(); - // wait remaining period + // wait period if (isStarted) { - try { TimeUnit.MILLISECONDS.sleep(that.periodInMs - (System.currentTimeMillis() - startTime)); } // target fixed period by accounting for run time + try { TimeUnit.MILLISECONDS.sleep(that.periodInMs - (targetFixedPeriod ? System.currentTimeMillis() - startTime : 0)); } // target fixed period by accounting for run time catch (Exception e) { isLooping = false; if (isStarted) throw new RuntimeException(e);