]> git.basschouten.com Git - openhab-addons.git/blob
98d78a0485a5f5148b01dd0ea397bc2c619c792e
[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.energidataservice.internal.retry.strategy;
14
15 import java.time.Clock;
16 import java.time.Duration;
17 import java.time.LocalDate;
18 import java.time.LocalDateTime;
19 import java.time.LocalTime;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.energidataservice.internal.retry.RetryStrategy;
24
25 /**
26  * This implements a {@link RetryStrategy} for a fixed time.
27  *
28  * @author Jacob Laursen - Initial contribution
29  */
30 @NonNullByDefault
31 public class FixedTime implements RetryStrategy {
32
33     private final Clock clock;
34
35     private LocalTime localTime;
36     private double jitter = 0.0;
37
38     public FixedTime(LocalTime localTime, Clock clock) {
39         this.localTime = localTime;
40         this.clock = clock;
41     }
42
43     @Override
44     public Duration getDuration() {
45         LocalTime now = LocalTime.now(clock);
46         LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(clock), localTime);
47         if (now.isAfter(localTime)) {
48             localDateTime = localDateTime.plusDays(1);
49         }
50
51         Duration base = Duration.between(LocalDateTime.now(clock), localDateTime);
52         if (jitter == 0.0) {
53             return base;
54         }
55
56         long duration = base.toMillis();
57         double rand = Math.random();
58         duration += (long) (rand * jitter * 1000 * 60);
59
60         return Duration.ofMillis(duration);
61     }
62
63     public FixedTime withJitter(double jitter) {
64         this.jitter = jitter;
65         return this;
66     }
67
68     @Override
69     public boolean equals(@Nullable Object o) {
70         if (o == this) {
71             return true;
72         }
73         if (!(o instanceof FixedTime)) {
74             return false;
75         }
76         FixedTime other = (FixedTime) o;
77
78         return this.jitter == other.jitter && this.localTime.equals(other.localTime);
79     }
80
81     @Override
82     public final int hashCode() {
83         final int result = 1;
84         return result;
85     }
86 }