]> git.basschouten.com Git - openhab-addons.git/blob
ed0152e90d8fed63c54967b7d35518324a2b312f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.tesla.internal.throttler;
14
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.concurrent.Executors;
18 import java.util.concurrent.Future;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.TimeUnit;
21
22 /**
23  * The {@link ScheduledChannelThrottler} implements a throttler that maintains a
24  * single execution rates, and does not maintain order of calls (thus has to
25  * start from back rather than try to insert things in middle)
26  *
27  * @author Karel Goderis - Initial contribution
28  */
29 public final class ScheduledChannelThrottler extends AbstractChannelThrottler {
30
31     public ScheduledChannelThrottler(Rate totalRate) {
32         this(totalRate, Executors.newSingleThreadScheduledExecutor(), new HashMap<>(), TimeProvider.SYSTEM_PROVIDER);
33     }
34
35     public ScheduledChannelThrottler(Rate totalRate, Map<Object, Rate> channels) {
36         this(totalRate, Executors.newSingleThreadScheduledExecutor(), channels, TimeProvider.SYSTEM_PROVIDER);
37     }
38
39     public ScheduledChannelThrottler(Rate totalRate, ScheduledExecutorService scheduler, Map<Object, Rate> channels,
40             TimeProvider timeProvider) {
41         super(totalRate, scheduler, channels, timeProvider);
42     }
43
44     public void submitSync(Object channelKey, Runnable task) throws InterruptedException {
45         Thread.sleep(getThrottleDelay(channelKey));
46         task.run();
47     }
48
49     public void submitSync(Runnable task) throws InterruptedException {
50         long delay = callTime(null) - timeProvider.getCurrentTimeInMillis();
51         Thread.sleep(getThrottleDelay(delay));
52         task.run();
53     }
54
55     @Override
56     public Future<?> submit(Runnable task) {
57         long delay = callTime(null) - timeProvider.getCurrentTimeInMillis();
58         return scheduler.schedule(task, delay < 0 ? 0 : delay, TimeUnit.MILLISECONDS);
59     }
60
61     @Override
62     public Future<?> submit(Object channelKey, Runnable task) {
63         return scheduler.schedule(task, getThrottleDelay(channelKey), TimeUnit.MILLISECONDS);
64     }
65 }