Search in sources :

Example 1 with ScheduledCompletableFuture

use of org.openhab.core.scheduler.ScheduledCompletableFuture in project openhab-core by openhab.

the class PersistenceManagerImpl method createTimers.

/**
 * Creates new {@link ScheduledCompletableFuture}s in the group <code>dbId</code> for the given collection of
 * {@link PersistenceStrategy strategies}.
 *
 * @param dbId the database id used by the persistence service
 * @param strategies a collection of strategies
 */
private void createTimers(final String dbId, List<PersistenceStrategy> strategies) {
    for (PersistenceStrategy strategy : strategies) {
        if (strategy instanceof PersistenceCronStrategy) {
            PersistenceCronStrategy cronStrategy = (PersistenceCronStrategy) strategy;
            String cronExpression = cronStrategy.getCronExpression();
            final PersistItemsJob job = new PersistItemsJob(this, dbId, cronStrategy.getName());
            ScheduledCompletableFuture<?> schedule = scheduler.schedule(job, cronExpression);
            if (persistenceJobs.containsKey(dbId)) {
                persistenceJobs.get(dbId).add(schedule);
            } else {
                final Set<ScheduledCompletableFuture<?>> jobs = new HashSet<>();
                jobs.add(schedule);
                persistenceJobs.put(dbId, jobs);
            }
            logger.debug("Scheduled strategy {} with cron expression {}", cronStrategy.getName(), cronExpression);
        }
    }
}
Also used : PersistenceCronStrategy(org.openhab.core.persistence.strategy.PersistenceCronStrategy) PersistenceStrategy(org.openhab.core.persistence.strategy.PersistenceStrategy) ScheduledCompletableFuture(org.openhab.core.scheduler.ScheduledCompletableFuture) HashSet(java.util.HashSet)

Example 2 with ScheduledCompletableFuture

use of org.openhab.core.scheduler.ScheduledCompletableFuture in project openhab-core by openhab.

the class SchedulerImplTest method testEarlyTrigger.

/**
 * This tests if the reschedule works correctly.
 * It does this by manipulating the duration calculation of the next step.
 * This causes the scheduler to reschedule the next call to early.
 * It then should match against the actual expected time and reschedule because the expected time is not reached.
 */
@Test
@Timeout(value = 15, unit = TimeUnit.SECONDS)
public void testEarlyTrigger() throws InterruptedException, ExecutionException {
    final TestSchedulerTemporalAdjuster temporalAdjuster = new TestSchedulerTemporalAdjuster(3000);
    final AtomicInteger counter = new AtomicInteger();
    final SchedulerImpl scheduler = new SchedulerImpl() {

        @Override
        protected long currentTimeMillis() {
            // This modification does mean it knows a bit about the internal implementation.
            return super.currentTimeMillis() + 3000;
        }
    };
    final AtomicReference<ScheduledCompletableFuture<Object>> reference = new AtomicReference<>();
    final ScheduledCompletableFuture<Object> future = scheduler.schedule(() -> counter.incrementAndGet(), temporalAdjuster);
    reference.set(future);
    future.get();
    assertEquals(3, temporalAdjuster.getCount(), "The next schedule caluclator should have been done 3 times.");
    assertEquals(3, counter.get(), "The schedule run method should have been called 3 times.");
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReference(java.util.concurrent.atomic.AtomicReference) ScheduledCompletableFuture(org.openhab.core.scheduler.ScheduledCompletableFuture) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 3 with ScheduledCompletableFuture

use of org.openhab.core.scheduler.ScheduledCompletableFuture in project openhab-core by openhab.

the class SchedulerImpl method before.

@Override
public <T> ScheduledCompletableFuture<T> before(CompletableFuture<T> promise, Duration timeout) {
    final AtomicBoolean done = new AtomicBoolean();
    final Consumer<Runnable> runOnce = runnable -> {
        if (!done.getAndSet(true)) {
            runnable.run();
        }
    };
    final ScheduledCompletableFutureOnce<T> wrappedPromise = new ScheduledCompletableFutureOnce<>(timeout);
    Callable<T> callable = () -> {
        wrappedPromise.completeExceptionally(new TimeoutException());
        return null;
    };
    final ScheduledCompletableFutureOnce<T> afterPromise = afterInternal(wrappedPromise, callable);
    wrappedPromise.exceptionally(e -> {
        if (e instanceof CancellationException) {
            // Also cancel the scheduled timer if returned completable future is cancelled.
            afterPromise.cancel(true);
        }
        return null;
    });
    // 
    promise.thenAccept(p -> runOnce.accept(() -> wrappedPromise.complete(p))).exceptionally(ex -> {
        runOnce.accept(() -> wrappedPromise.completeExceptionally(ex));
        return null;
    });
    return wrappedPromise;
}
Also used : SchedulerRunnable(org.openhab.core.scheduler.SchedulerRunnable) ScheduledFuture(java.util.concurrent.ScheduledFuture) ZonedDateTime(java.time.ZonedDateTime) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Component(org.osgi.service.component.annotations.Component) Nullable(org.eclipse.jdt.annotation.Nullable) Scheduler(org.openhab.core.scheduler.Scheduler) Duration(java.time.Duration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Delayed(java.util.concurrent.Delayed) ThreadPoolManager(org.openhab.core.common.ThreadPoolManager) ScheduledCompletableFuture(org.openhab.core.scheduler.ScheduledCompletableFuture) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Logger(org.slf4j.Logger) CancellationException(java.util.concurrent.CancellationException) SchedulerTemporalAdjuster(org.openhab.core.scheduler.SchedulerTemporalAdjuster) Instant(java.time.Instant) ZoneId(java.time.ZoneId) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ChronoUnit(java.time.temporal.ChronoUnit) Temporal(java.time.temporal.Temporal) TemporalAdjuster(java.time.temporal.TemporalAdjuster) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CancellationException(java.util.concurrent.CancellationException) SchedulerRunnable(org.openhab.core.scheduler.SchedulerRunnable) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with ScheduledCompletableFuture

use of org.openhab.core.scheduler.ScheduledCompletableFuture in project openhab-core by openhab.

the class SchedulerImplTest method testBeforeResolvedWithException.

@Test
@Timeout(value = 300, unit = TimeUnit.MILLISECONDS)
public void testBeforeResolvedWithException() throws InterruptedException {
    CompletableFuture<Integer> d = new CompletableFuture<>();
    ScheduledCompletableFuture<Integer> before = scheduler.before(d, Duration.ofMillis(100));
    // Pass an exception not very likely thrown by the scheduler it self to avoid missing real exceptions.
    d.completeExceptionally(new FileNotFoundException("testBeforeTimeoutException"));
    assertTrue(before.isDone(), "Scheduled job should be done");
    assertTrue(before.getPromise().isCompletedExceptionally(), "Before CompletableFuture should have completed with an exception");
    assertThrows(FileNotFoundException.class, () -> {
        try {
            before.get();
        } catch (ExecutionException e) {
            throw e.getCause();
        }
    });
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java.util.concurrent.CompletableFuture) ScheduledCompletableFuture(org.openhab.core.scheduler.ScheduledCompletableFuture) FileNotFoundException(java.io.FileNotFoundException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Aggregations

ScheduledCompletableFuture (org.openhab.core.scheduler.ScheduledCompletableFuture)4 CompletableFuture (java.util.concurrent.CompletableFuture)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Test (org.junit.jupiter.api.Test)2 Timeout (org.junit.jupiter.api.Timeout)2 FileNotFoundException (java.io.FileNotFoundException)1 Duration (java.time.Duration)1 Instant (java.time.Instant)1 ZoneId (java.time.ZoneId)1 ZonedDateTime (java.time.ZonedDateTime)1 ChronoUnit (java.time.temporal.ChronoUnit)1 Temporal (java.time.temporal.Temporal)1 TemporalAdjuster (java.time.temporal.TemporalAdjuster)1 HashSet (java.util.HashSet)1 Callable (java.util.concurrent.Callable)1 CancellationException (java.util.concurrent.CancellationException)1 Delayed (java.util.concurrent.Delayed)1 ExecutionException (java.util.concurrent.ExecutionException)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 ScheduledFuture (java.util.concurrent.ScheduledFuture)1