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 heatup for any effect you need. I.e., something happens and you need to pursue
7    * some behavior/effect for amount of time. Just create heatup with specified amount of time 
8    * "for the heat" and use {@link Heatup#isHot()} to check whether you should still be using your behavior/effect.
9    * <p><p>
10   * To make your heatup hot, just call {@link Heatup#heat()}.
11   * 
12   * @author Jimmy
13   */
14  public class Heatup {
15  
16  	/**
17  	 * How long is the heatup.
18  	 */
19  	private long heatupMillis;
20  	
21  	/**
22  	 * When the cooldown was last used.
23  	 */
24  	private long lastUsedMillis;
25  
26  	public Heatup(long cooldownMillis) {
27  		this(cooldownMillis, TimeUnit.MILLISECONDS);
28  	}
29  
30  	public Heatup(long cooldownTime, TimeUnit timeUnit) {
31  		switch(timeUnit) {
32  		case DAYS: this.heatupMillis = cooldownTime * 24 * 60 * 60 * 1000; break;
33  		case HOURS: this.heatupMillis = cooldownTime * 60 * 60 * 1000; break;
34  		case MICROSECONDS: throw new UnsupportedOperationException("Unsupported: MICROSECONDS.");
35  		case MILLISECONDS: this.heatupMillis = cooldownTime; break;
36  		case MINUTES: this.heatupMillis = cooldownTime * 60 * 1000; break;
37  		case NANOSECONDS:  throw new UnsupportedOperationException("Unsupported: NANOSECONDS.");
38  		case SECONDS: this.heatupMillis = cooldownTime * 1000; break;
39  		}
40  	}
41  	
42  	/**
43  	 * Check whether it is still hot.
44  	 * @return
45  	 */
46  	public boolean isHot() {
47  		return (System.currentTimeMillis() - lastUsedMillis < heatupMillis);
48  	}
49  	
50  	/**
51  	 * Force use of the effect == sets {@link Heatup#lastUsedMillis} to current time.
52  	 */
53  	public void heat() {
54  		lastUsedMillis = System.currentTimeMillis();
55  	}
56  	
57  	/**
58  	 * How much time we still have until the object becomes cold, i.e., !{@link Heatup#isHot()}.
59  	 * @return
60  	 */
61  	public long getRemainingTime() {
62  		if (!isHot()) return 0;
63  		return heatupMillis - (System.currentTimeMillis() - lastUsedMillis);
64  	}
65  
66  	/**
67  	 * Removes the heat...
68  	 */
69  	public void clear() {
70  		lastUsedMillis = 0;
71  	}
72  
73  	/**
74  	 * Check whether we're cool == !{@link Heatup#isHot()}.
75  	 * @return
76  	 */
77  	public boolean isCool() {
78  		return !isHot();
79  	}
80  	
81  }