View Javadoc

1   package cz.cuni.amis.utils;
2   
3   import java.util.concurrent.TimeUnit;
4   
5   /**
6    * This class allows you to easily setup cooldown for any effect you need. Just create cooldown with specified amount of time 
7    * "for the cooldown" and use {@link Cooldown#tryUse()} to check whether you may use your effect now.
8    * <p><p>
9    * Opposite functionality (doing something until some time passes by) is captured by {@link Heatup}.
10   * 
11   * @author Jimmy
12   */
13  /**
14   * @author Jimmy
15   *
16   */
17  public class Cooldown {
18  
19  	/**
20  	 * How long is the cooldown.
21  	 */
22  	private long cooldownMillis;
23  	
24  	/**
25  	 * When the cooldown was last used.
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  	 * Check whether it is {@link Cooldown#isCool()}, if so, save current time as the time of the use and returns true,
47  	 * otherwise (== effect needs more cooldown, see {@link Cooldown#getRemainingTime()}) returns false.
48  	 * @return
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  	 * Force use of the effect == sets {@link Cooldown#lastUsedMillis} to current time.
61  	 */
62  	public void use() {
63  		lastUsedMillis = System.currentTimeMillis();
64  	}
65  	
66  	/**
67  	 * Whether you may use the effect, i.e., it was never used before or has cooled down.
68  	 * @return
69  	 */
70  	public boolean isCool() {
71  		return (System.currentTimeMillis() - lastUsedMillis >= cooldownMillis);
72  	}
73  	
74  	/**
75  	 * Whether we're not {@link Cooldown#isCool()}.
76  	 */
77  	public boolean isHot() {
78  		return !isCool();
79  	}
80  	
81  	/**
82  	 * How much time we need to wait before the effect will cool down.
83  	 * @return
84  	 */
85  	public long getRemainingTime() {
86  		if (isCool()) return 0;
87  		return cooldownMillis - (System.currentTimeMillis() - lastUsedMillis);
88  	}
89  	
90  	/**
91  	 * Cools down totally.
92  	 */
93  	public void clear() {
94  		lastUsedMillis = 0;
95  	}
96  	
97  }