2 * Copyright (c) 2010-2022 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.homematic.internal.misc;
15 import java.io.IOException;
16 import java.util.HashMap;
18 import java.util.Timer;
19 import java.util.TimerTask;
21 import org.openhab.binding.homematic.internal.model.HmDatapointInfo;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * Executes a callback method either immediately or after a given delay for a datapoint.
28 * @author Gerhard Riegler - Initial contribution
30 public class DelayedExecuter {
31 private final Logger logger = LoggerFactory.getLogger(DelayedExecuter.class);
33 private Map<HmDatapointInfo, Timer> delayedEvents = new HashMap<>();
36 * Executes a callback method either immediately or after a given delay.
38 public void start(final HmDatapointInfo dpInfo, final double delay, final DelayedExecuterCallback callback)
39 throws IOException, HomematicClientException {
41 synchronized (DelayedExecuter.class) {
42 logger.debug("Delaying event for {} seconds: '{}'", delay, dpInfo);
44 Timer timer = delayedEvents.get(dpInfo);
50 delayedEvents.put(dpInfo, timer);
51 timer.schedule(new TimerTask() {
54 logger.debug("Executing delayed event for '{}'", dpInfo);
55 delayedEvents.remove(dpInfo);
58 } catch (Exception ex) {
59 logger.error("{}", ex.getMessage(), ex);
62 }, (long) (delay * 1000));
70 * Stops all delayed events.
73 for (Timer timer : delayedEvents.values()) {
76 delayedEvents.clear();
80 * Callback interface for the {@link DelayedExecuter}.
82 * @author Gerhard Riegler - Initial contribution
84 public interface DelayedExecuterCallback {
86 public void execute() throws IOException, HomematicClientException;