This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimerSignaling.java
executable file
·98 lines (88 loc) · 2.43 KB
/
TimerSignaling.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
*
*/
package rs.eventbroker.queue;
import java.util.Calendar;
import java.util.concurrent.Executor;
import rs.baselib.util.RsDate;
import rs.eventbroker.service.EventData;
/**
* A long-time running worker that signal every minute for timing events.
* <p>Purpose is to implement cron-alike events. Topics look like:</p>
* <pre>timer/min/40/hour/14/day/3/weekday/1/month/11</pre>
* <p> where weekdays are indexed (Sun=1 ... Sat=7) and months are zero-based
* indices (Jan=0 ... Dec=11). The payload is the timezone of this information, e.g. Europe/Berlin.</p>
*
* @author ralph
*
*/
public class TimerSignaling implements Runnable {
private volatile boolean stopRunning = false;
/** The executor for worker threads */
protected Executor executor = null;
/**
* Constructor.
* @param executor - the executor that will handle events.
*/
public TimerSignaling(Executor executor) {
this.executor = executor;
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
while (!stopRunning) {
RsDate now = new RsDate();
// Loop until the next full minute
while (!stopRunning && (now.get(Calendar.SECOND) > 0)) {
// Sleep until next second
waitSecond();
now = new RsDate();
}
// We shall now be at a full minute
if (!stopRunning) {
EventData event = new EventData();
event.setPacketId("TIMER-"+now.getTimeInMillis());
StringBuilder topic = new StringBuilder();
topic.append("timer/min/");
topic.append(now.get(Calendar.MINUTE));
topic.append("/hour/");
topic.append(now.get(Calendar.HOUR_OF_DAY));
topic.append("/day/");
topic.append(now.get(Calendar.DAY_OF_MONTH));
topic.append("/weekday/");
topic.append(now.get(Calendar.DAY_OF_WEEK));
topic.append("/month/");
topic.append(now.get(Calendar.MONTH)+1);
event.setTopicName(topic.toString());
event.setPayload(now.getTimeZone().getID());
event.setQos(0);
event.setRetainFlag(false);
event.setDupFlag(false);
executor.execute(new EventHandler(executor, event));
// Sleep until next second
waitSecond();
now = new RsDate();
}
}
}
/**
* Waits until the next second.
*/
private static void waitSecond() {
// Sleep until next second
int ms = 1100 - new RsDate().get(Calendar.MILLISECOND);
try {
Thread.sleep(ms);
} catch (Throwable t) {
// Ignore silently
}
}
/**
* Stop this timer signaling.
*/
public void stopRunning() {
this.stopRunning = true;
}
}