1 package cz.cuni.amis.utils;
2
3 import java.util.concurrent.TimeUnit;
4
5
6
7
8
9
10
11
12
13
14
15
16
17 public class Cooldown {
18
19
20
21
22 private long cooldownMillis;
23
24
25
26
27 private long lastUsedMillis;
28
29 public Cooldown(long cooldownMillis) {
30 this(cooldownMillis, TimeUnit.MILLISECONDS);
31 }
32
33 public Cooldown(long cooldownTime, TimeUnit timeUnit) {
34 switch(timeUnit) {
35 case DAYS: this.cooldownMillis = cooldownTime * 24 * 60 * 60 * 1000; break;
36 case HOURS: this.cooldownMillis = cooldownTime * 60 * 60 * 1000; break;
37 case MICROSECONDS: throw new UnsupportedOperationException("Unsupported: MICROSECONDS.");
38 case MILLISECONDS: this.cooldownMillis = cooldownTime; break;
39 case MINUTES: this.cooldownMillis = cooldownTime * 60 * 1000; break;
40 case NANOSECONDS: throw new UnsupportedOperationException("Unsupported: NANOSECONDS.");
41 case SECONDS: this.cooldownMillis = cooldownTime * 1000; break;
42 }
43 }
44
45
46
47
48
49
50 public boolean tryUse() {
51 long time = System.currentTimeMillis();
52 if (time - lastUsedMillis >= cooldownMillis) {
53 this.lastUsedMillis = time;
54 return true;
55 }
56 return false;
57 }
58
59
60
61
62 public void use() {
63 lastUsedMillis = System.currentTimeMillis();
64 }
65
66
67
68
69
70 public boolean isCool() {
71 return (System.currentTimeMillis() - lastUsedMillis >= cooldownMillis);
72 }
73
74
75
76
77 public boolean isHot() {
78 return !isCool();
79 }
80
81
82
83
84
85 public long getRemainingTime() {
86 if (isCool()) return 0;
87 return cooldownMillis - (System.currentTimeMillis() - lastUsedMillis);
88 }
89
90
91
92
93 public void clear() {
94 lastUsedMillis = 0;
95 }
96
97 }