forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJobTrigger.java
More file actions
498 lines (418 loc) · 16 KB
/
JobTrigger.java
File metadata and controls
498 lines (418 loc) · 16 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
package act.job;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static act.app.event.SysEventId.START;
import static act.app.event.SysEventId.STOP;
import static act.job.JobManager.sysEventJobId;
import act.app.App;
import act.app.event.SysEventId;
import act.conf.AppConfig;
import act.event.SysEventListenerBase;
import fc.cron.CronExpression;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.osgl.$;
import org.osgl.exception.NotAppliedException;
import org.osgl.logging.LogManager;
import org.osgl.logging.Logger;
import org.osgl.util.E;
import org.osgl.util.S;
import org.rythmengine.utils.Time;
import java.util.EventObject;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* A `JobTrigger` triggers a {@link Job} to be executed
*/
public abstract class JobTrigger {
protected static final Logger LOGGER = LogManager.get(JobTrigger.class);
@Override
public String toString() {
return getClass().getSimpleName();
}
protected static boolean isTraceEnabled() {
return LOGGER.isTraceEnabled();
}
protected static void trace(String msg, Object... args) {
LOGGER.trace(msg, args);
}
final void register(Job job, JobManager manager) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("trigger on [%s]: %s", this, job);
}
job.trigger(this);
schedule(manager, job);
}
void scheduleFollowingCalls(JobManager manager, Job job) {}
void schedule(JobManager manager, Job job) {}
void traceSchedule(Job job) {
if (isTraceEnabled()) {
trace("trigger[%s] schedule job: %s", this, job);
}
}
static JobTrigger of(AppConfig config, Cron anno) {
String v = anno.value();
if (v.startsWith("cron.")) {
v = (String) config.get(v);
} else if (v.startsWith("${") && v.endsWith("}")) {
v = v.substring(2, v.length() - 1);
v = (String) config.get(v);
}
if (S.blank(v)) {
throw E.invalidConfiguration("Cannot find configuration for cron: %s", anno.value());
}
return cron(v);
}
static JobTrigger of(AppConfig config, OnAppStart anno) {
int delayInSeconds = anno.delayInSeconds();
if (delayInSeconds > 0) {
return delayAfter(START, delayInSeconds);
}
if (anno.async()) {
return alongWith(START);
} else {
return after(START);
}
}
static JobTrigger of(AppConfig config, OnAppStop anno) {
if (anno.async()) {
return alongWith(STOP);
} else {
return before(STOP);
}
}
static JobTrigger of(AppConfig config, FixedDelay anno) {
String delay = anno.value();
if (delay.startsWith("delay.")) {
delay = (String) config.get(delay);
} else if (delay.startsWith("${") && delay.endsWith("}")) {
delay = delay.substring(2, delay.length() - 1);
delay = (String) config.get(delay);
}
if (S.blank(delay)) {
throw E.invalidConfiguration("Cannot find configuration for delay: %s", anno.value());
}
return fixedDelay(delay, anno.startImmediately());
}
static JobTrigger of(AppConfig config, Every anno) {
String duration = anno.value();
if (duration.startsWith("every.")) {
duration = (String) config.get(duration);
} else if (duration.startsWith("${") && duration.endsWith("}")) {
duration = duration.substring(2, duration.length() - 1);
duration = (String) config.get(duration);
}
if (S.blank(duration)) {
throw E.invalidConfiguration("Cannot find configuration for duration: %s", anno.value());
}
return every(duration, anno.startImmediately());
}
static JobTrigger of(AppConfig config, AlongWith anno) {
String id = anno.value();
E.illegalArgumentIf(S.blank(id), "associate job ID cannot be empty");
int delayInSeconds = anno.delayInSeconds();
if (delayInSeconds > 0) {
return new _DelayAfter(id, delayInSeconds);
} else {
return new _AlongWith(id);
}
}
static JobTrigger of(AppConfig config, InvokeAfter anno) {
String id = anno.value();
E.illegalArgumentIf(S.blank(id), "associate job ID cannot be empty");
return new _After(id);
}
static JobTrigger of(AppConfig config, InvokeBefore anno) {
String id = anno.value();
E.illegalArgumentIf(S.blank(id), "associate job ID cannot be empty");
return new _Before(id);
}
static JobTrigger cron(String expression) {
return new _Cron(expression);
}
static JobTrigger fixedDelay(String duration, boolean startImmediately) {
return new _FixedDelay(duration, startImmediately);
}
static JobTrigger fixedDelay(long seconds, boolean startImmediately) {
return new _FixedDelay(seconds, startImmediately);
}
static JobTrigger fixedDelay(long interval, TimeUnit timeUnit, boolean startImmediately) {
return new _FixedDelay(timeUnit.toSeconds(interval), startImmediately);
}
static JobTrigger every(String duration, boolean startImmediately) {
return new _Every(duration, startImmediately);
}
static JobTrigger every(long seconds, boolean startImmediately) {
return new _Every(seconds, TimeUnit.SECONDS, startImmediately);
}
static JobTrigger every(long duration, TimeUnit timeUnit, boolean startImmediately) {
return new _Every(duration, timeUnit, startImmediately);
}
static JobTrigger onAppStart(boolean async, int delayInSeconds) {
if (delayInSeconds > 0) {
return delayAfter(START, delayInSeconds);
}
return async ? alongWith(START) : after(START);
}
static JobTrigger onAppStop(boolean async) {
return async ? alongWith(STOP) : before(STOP);
}
static JobTrigger onSysEvent(SysEventId eventId, boolean async) {
return async ? alongWith(eventId) : after(eventId);
}
static JobTrigger delayForSeconds(long seconds, boolean startImmediately) {
return new _FixedDelay(seconds, startImmediately);
}
static JobTrigger alongWith(String jobId) {
return new _AlongWith(jobId);
}
static JobTrigger alongWith(SysEventId sysEvent) {
return new _AlongWith(sysEventJobId(sysEvent));
}
static JobTrigger before(String jobId) {
return new _Before(jobId);
}
static JobTrigger before(SysEventId sysEvent) {
return before(sysEventJobId(sysEvent));
}
static JobTrigger after(String jobId) {
return new _After(jobId);
}
static JobTrigger after(SysEventId sysEvent) {
return after(sysEventJobId(sysEvent));
}
static JobTrigger delayAfter(String jobId, int delayInSeconds) {
return new _DelayAfter(jobId, delayInSeconds);
}
static JobTrigger delayAfter(SysEventId sysEvent, int delayInSeconds) {
return delayAfter(sysEventJobId(sysEvent), delayInSeconds);
}
static class _Cron extends JobTrigger {
private CronExpression cronExpr;
_Cron(String expression) {
cronExpr = new CronExpression(expression);
}
@Override
public String toString() {
return S.newBuffer("cron :").a(cronExpr).toString();
}
@Override
void schedule(final JobManager manager, final Job job) {
traceSchedule(job);
App app = manager.app();
if (!app.isStarted()) {
app.eventBus().bindAsync(SysEventId.POST_START, new SysEventListenerBase() {
@Override
public void on(EventObject event) throws Exception {
delayedSchedule(manager, job);
}
});
} else {
delayedSchedule(manager, job);
}
}
private void delayedSchedule(JobManager manager, Job job) {
DateTime now = DateTime.now();
// add one seconds to prevent the next time be the current time (now)
DateTime next = cronExpr.nextTimeAfter(now.plusSeconds(1));
Seconds seconds = Seconds.secondsBetween(now, next);
ScheduledFuture future = manager.executor().schedule(job, seconds.getSeconds(), TimeUnit.SECONDS);
manager.futureScheduled(job.id(), future);
}
@Override
void scheduleFollowingCalls(JobManager manager, Job job) {
schedule(manager, job);
}
}
private abstract static class _Periodical extends JobTrigger {
protected long seconds;
protected boolean startImmediately;
_Periodical(String duration, boolean startImmediately) {
E.illegalArgumentIf(S.blank(duration), "delay duration shall not be empty");
seconds = Time.parseDuration(duration);
E.illegalArgumentIf(seconds < 1, "delay duration shall not be zero or negative number");
this.startImmediately = startImmediately;
}
_Periodical(long seconds, boolean startImmediately) {
E.illegalArgumentIf(seconds < 1, "delay duration cannot be zero or negative");
this.seconds = seconds;
this.startImmediately = startImmediately;
}
@Override
final void schedule(final JobManager manager, final Job job) {
traceSchedule(job);
App app = manager.app();
if (!app.isStarted()) {
app.eventBus().bindAsync(SysEventId.POST_START, new SysEventListenerBase() {
@Override
public void on(EventObject event) {
runAndSchedule(manager, job);
}
});
} else {
runAndSchedule(manager, job);
}
}
protected abstract void delayedSchedule(JobManager manager, Job job);
protected void runAndSchedule(JobManager manager, Job job) {
if (startImmediately) {
manager.now(job);
}
delayedSchedule(manager, job);
}
}
private static class _FixedDelay extends _Periodical {
_FixedDelay(String duration, boolean startImmediately) {
super(duration, startImmediately);
}
_FixedDelay(long seconds, boolean startImmediately) {
super(seconds, startImmediately);
}
@Override
public String toString() {
return S.concat("fixed delay of ", S.string(seconds), " seconds");
}
@Override
protected void delayedSchedule(JobManager manager, Job job) {
ScheduledThreadPoolExecutor executor = manager.executor();
ScheduledFuture future = executor.scheduleWithFixedDelay(job, seconds, seconds, TimeUnit.SECONDS);
manager.futureScheduled(job.id(), future);
}
}
private static class _Every extends _Periodical {
_Every(String duration, boolean startImmediately) {
super(duration, startImmediately);
}
_Every(long duration, TimeUnit timeUnit, boolean startImmediately) {
super(timeUnit.toSeconds(duration), startImmediately);
}
@Override
public String toString() {
return S.concat("every ", S.string(seconds), " seconds");
}
@Override
protected void delayedSchedule(JobManager manager, Job job) {
ScheduledThreadPoolExecutor executor = manager.executor();
ScheduledFuture future = executor.scheduleAtFixedRate(job, seconds, seconds, TimeUnit.SECONDS);
manager.futureScheduled(job.id(), future);
}
}
private abstract static class _AssociatedTo extends JobTrigger {
String targetId;
_AssociatedTo(String targetId) {
E.illegalArgumentIf(S.blank(targetId), "associate job ID expected");
this.targetId = targetId;
}
@Override
void schedule(JobManager manager, Job job) {
traceSchedule(job);
if (null == targetId) {
LOGGER.warn("Failed to register job because target job not found: %s. Will try again after app started", targetId);
scheduleDelayedRegister(manager, job);
} else {
Job associateTarget = manager.jobById(targetId);
if (null == associateTarget) {
LOGGER.warn("Cannot find associated job: %s", targetId);
} else {
associate(job, associateTarget);
}
}
}
private void scheduleDelayedRegister(final JobManager manager, final Job job) {
final String id = delayedRegisterJobId(job);
before(START).register(new Job(id, manager, new $.F0<Void>() {
@Override
public Void apply() throws NotAppliedException, $.Break {
Job associateTo = manager.jobById(id);
if (null == associateTo) {
LOGGER.warn("Cannot find associated job: %s", id);
} else {
associate(job, associateTo);
}
return null;
}
}), manager);
}
private String delayedRegisterJobId(Job job) {
return S.concat("delayed_association_register-", job.id(), "-to-", targetId);
}
abstract void associate(Job theJob, Job toJob);
}
private static class _AlongWith extends _AssociatedTo {
_AlongWith(String targetId) {
super(targetId);
}
@Override
public String toString() {
return S.concat("along with ", targetId);
}
@Override
void associate(Job theJob, Job toJob) {
toJob.addParallelJob(theJob);
}
}
private static class _Before extends _AssociatedTo {
_Before(String targetId) {
super(targetId);
}
@Override
public String toString() {
return S.concat("before ", targetId);
}
@Override
void associate(Job theJob, Job toJob) {
toJob.addPrecedenceJob(theJob);
}
}
private static class _After extends _AssociatedTo {
_After(String targetId) {
super(targetId);
}
@Override
public String toString() {
return S.concat("after ", targetId);
}
@Override
void associate(Job theJob, Job toJob) {
toJob.addFollowingJob(theJob);
}
}
private static class _DelayAfter extends _AssociatedTo {
private int delayInSeconds;
_DelayAfter(String targetId, int delayInSeconds) {
super(targetId);
this.delayInSeconds = delayInSeconds;
}
@Override
public String toString() {
return S.concat("delay %ss after ", delayInSeconds, targetId);
}
@Override
void associate(final Job theJob, final Job toJob) {
toJob.addPrecedenceJob(new Job(toJob.id() + "-delay-" + delayInSeconds, toJob.manager()) {
@Override
public void run() {
toJob.manager().delay(theJob, delayInSeconds, TimeUnit.SECONDS);
}
});
}
}
}