Skip to content

Commit

Permalink
TaskLooper does not target fixed period by default
Browse files Browse the repository at this point in the history
  • Loading branch information
woodser committed Apr 25, 2024
1 parent 007a199 commit 6d1de0b
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/main/java/monero/common/TaskLooper.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,26 @@ public TaskLooper(Runnable task) {
public Runnable getTask() {
return task;
}

/**
* Start the task loop.
*
* @param periodInMs the loop period in milliseconds
* @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;
Expand All @@ -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);
Expand Down

0 comments on commit 6d1de0b

Please sign in to comment.