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.chromecast.internal;
15 import java.util.concurrent.ScheduledExecutorService;
16 import java.util.concurrent.ScheduledFuture;
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;
22 import org.slf4j.LoggerFactory;
25 * Handles scheduling of connect and refresh events.
27 * @author Jason Holmes - Initial contribution
28 * @author Wouter Born - Make sure only at most one refresh job is scheduled and running
31 public class ChromecastScheduler {
32 private final Logger logger = LoggerFactory.getLogger(ChromecastScheduler.class);
34 private final ScheduledExecutorService scheduler;
35 private final long connectDelay;
36 private final long refreshRate;
37 private final Runnable connectRunnable;
38 private final Runnable refreshRunnable;
40 private @Nullable ScheduledFuture<?> connectFuture;
41 private @Nullable ScheduledFuture<?> refreshFuture;
43 public ChromecastScheduler(ScheduledExecutorService scheduler, long connectDelay, Runnable connectRunnable,
44 long refreshRate, Runnable refreshRunnable) {
45 this.scheduler = scheduler;
46 this.connectDelay = connectDelay;
47 this.connectRunnable = connectRunnable;
48 this.refreshRate = refreshRate;
49 this.refreshRunnable = refreshRunnable;
52 public synchronized void destroy() {
57 public synchronized void scheduleConnect() {
59 logger.debug("Scheduling connection");
60 connectFuture = scheduler.schedule(connectRunnable, connectDelay, TimeUnit.SECONDS);
63 private synchronized void cancelConnect() {
64 logger.debug("Canceling connection");
65 ScheduledFuture<?> localConnectFuture = connectFuture;
66 if (localConnectFuture != null) {
67 localConnectFuture.cancel(true);
72 public synchronized void scheduleRefresh() {
74 logger.debug("Scheduling refresh in {} seconds", refreshRate);
75 // With an initial delay of 1 second the refresh job can be restarted when several channels are refreshed at
76 // once e.g. due to channel linking
77 refreshFuture = scheduler.scheduleWithFixedDelay(refreshRunnable, 1, refreshRate, TimeUnit.SECONDS);
80 public synchronized void cancelRefresh() {
81 logger.debug("Canceling refresh");
82 ScheduledFuture<?> localRefreshFuture = refreshFuture;
83 if (localRefreshFuture != null) {
84 localRefreshFuture.cancel(true);