This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 4a6b9d3  CAMEL-17221: added support for a repeatable task that stops 
upon return
4a6b9d3 is described below

commit 4a6b9d304ff51cf6e0bb3a7ef646fe9813e5992c
Author: Otavio Rodolfo Piske <[email protected]>
AuthorDate: Tue Nov 9 17:05:50 2021 +0100

    CAMEL-17221: added support for a repeatable task that stops upon return
---
 .../apache/camel/support/task/ForegroundTask.java  | 36 ++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git 
a/core/camel-support/src/main/java/org/apache/camel/support/task/ForegroundTask.java
 
b/core/camel-support/src/main/java/org/apache/camel/support/task/ForegroundTask.java
index 5b1935b..d2ac9dc 100644
--- 
a/core/camel-support/src/main/java/org/apache/camel/support/task/ForegroundTask.java
+++ 
b/core/camel-support/src/main/java/org/apache/camel/support/task/ForegroundTask.java
@@ -17,8 +17,10 @@
 
 package org.apache.camel.support.task;
 
+import java.util.Optional;
 import java.util.function.BooleanSupplier;
 import java.util.function.Predicate;
+import java.util.function.Supplier;
 
 import org.apache.camel.support.task.budget.IterationBudget;
 import org.slf4j.Logger;
@@ -120,4 +122,38 @@ public class ForegroundTask implements BlockingTask {
 
         return completed;
     }
+
+    /**
+     * Run a task until it produces a result
+     * 
+     * @param  supplier  the supplier of the result
+     * @param  predicate a predicate to test if the result is acceptable
+     * @param  <T>       the type for the result
+     * @return           An optional with the result
+     */
+    public <T> Optional<T> run(Supplier<T> supplier, Predicate<T> predicate) {
+        try {
+            if (budget.initialDelay() > 0) {
+                Thread.sleep(budget.initialDelay());
+            }
+
+            while (budget.next()) {
+                T ret = supplier.get();
+                if (predicate.test(ret)) {
+                    LOG.info("Task {} is complete after {} iterations and it 
is ready to continue",
+                            name, budget.iteration());
+                    return Optional.ofNullable(ret);
+                }
+
+                if (budget.canContinue()) {
+                    Thread.sleep(budget.interval());
+                }
+            }
+        } catch (InterruptedException e) {
+            LOG.warn("Interrupted {} while waiting for the repeatable task to 
execute", name);
+            Thread.currentThread().interrupt();
+        }
+
+        return Optional.empty();
+    }
 }

Reply via email to