2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ecovacs.internal.api.util;
15 import java.util.concurrent.Future;
16 import java.util.concurrent.ScheduledExecutorService;
17 import java.util.concurrent.TimeUnit;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.slf4j.Logger;
24 * @author Danny Baumann - Initial contribution
27 public class SchedulerTask implements Runnable {
28 private final Logger logger;
29 private final String name;
30 private String prefixedName;
31 private final Runnable runnable;
32 private final ScheduledExecutorService scheduler;
33 private @Nullable Future<?> future;
35 public SchedulerTask(ScheduledExecutorService scheduler, Logger logger, String name, Runnable runnable) {
38 this.prefixedName = name;
39 this.runnable = runnable;
40 this.scheduler = scheduler;
43 public void setNamePrefix(String prefix) {
45 throw new IllegalStateException("Must not set prefix while scheduled");
47 if (prefix.isEmpty()) {
50 prefixedName = prefix + ": " + name;
54 public void submit() {
58 public synchronized void schedule(long delaySeconds) {
60 logger.trace("{}: Already scheduled to run", prefixedName);
63 logger.trace("{}: Scheduling to run in {} seconds", prefixedName, delaySeconds);
64 if (delaySeconds == 0) {
65 future = scheduler.submit(this);
67 future = scheduler.schedule(this, delaySeconds, TimeUnit.SECONDS);
71 public synchronized void scheduleRecurring(long intervalSeconds) {
73 logger.trace("{}: Already scheduled to run", prefixedName);
76 logger.trace("{}: Scheduling to run in {} second intervals", prefixedName, intervalSeconds);
77 future = scheduler.scheduleWithFixedDelay(runnable, 0, intervalSeconds, TimeUnit.SECONDS);
80 public synchronized void cancel() {
81 Future<?> future = this.future;
85 logger.trace("{}: Cancelled", prefixedName);
94 logger.trace("{}: Running one-shot", prefixedName);