forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppJobManager.java
More file actions
474 lines (405 loc) · 15.2 KB
/
AppJobManager.java
File metadata and controls
474 lines (405 loc) · 15.2 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
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 act.Act;
import act.Destroyable;
import act.app.App;
import act.app.AppServiceBase;
import act.app.AppThreadFactory;
import act.app.event.AppEventId;
import act.event.AppEventListenerBase;
import act.event.OnceEventListenerBase;
import act.mail.MailerContext;
import act.util.ProgressGauge;
import act.util.SimpleProgressGauge;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.osgl.$;
import org.osgl.Osgl;
import org.osgl.exception.NotAppliedException;
import org.osgl.logging.LogManager;
import org.osgl.logging.Logger;
import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.S;
import org.rythmengine.utils.Time;
import java.util.EventObject;
import java.util.Map;
import java.util.concurrent.*;
public class AppJobManager extends AppServiceBase<AppJobManager> {
private static final Logger LOGGER = LogManager.get(AppJobManager.class);
private ScheduledThreadPoolExecutor executor;
private ConcurrentMap<String, Job> jobs = new ConcurrentHashMap<String, Job>();
private ConcurrentMap<String, ScheduledFuture> scheduled = new ConcurrentHashMap<>();
static String appEventJobId(AppEventId eventId) {
return S.concat("__act_app__", eventId.toString().toLowerCase());
}
public AppJobManager(App app) {
super(app);
initExecutor(app);
for (AppEventId appEventId : AppEventId.values()) {
createAppEventListener(appEventId);
}
}
@Override
protected void releaseResources() {
LOGGER.trace("release job manager resources");
for (Job job : jobs.values()) {
job.destroy();
}
jobs.clear();
executor.getQueue().clear();
executor.shutdownNow();
}
public <T> Future<T> now(Callable<T> callable) {
return executor().submit(callable);
}
public void now(Runnable runnable) {
executor().submit(wrap(runnable));
}
public String now($.Function<ProgressGauge, ?> worker) {
Job job = wrap(worker);
addJob(job);
executor().submit(job);
return job.id();
}
/**
* Prepare a job from worker. This function will return
* a job ID and can be used to feed into the {@link #now(String)}
* call
*
* @param worker the worker
* @return the job ID allocated
*/
public String prepare($.Function<ProgressGauge, ?> worker) {
Job job = wrap(worker);
addJob(job);
return job.id();
}
/**
* Run a job by ID now
* @param jobId the job ID
* @see #prepare(Osgl.Function)
*/
public void now(String jobId) {
Job job = $.notNull(jobById(jobId));
executor().submit(job);
}
public <T> Future<T> delay(Callable<T> callable, long delay, TimeUnit timeUnit) {
return executor().schedule(callable, delay, timeUnit);
}
public void delay(Runnable runnable, long delay, TimeUnit timeUnit) {
executor().schedule(wrap(runnable), delay, timeUnit);
}
public <T> Future<T> delay(Callable<T> callable, String delay) {
int seconds = parseTime(delay);
return executor().schedule(callable, seconds, TimeUnit.SECONDS);
}
public void delay(Runnable runnable, String delay) {
int seconds = parseTime(delay);
executor().schedule(wrap(runnable), seconds, TimeUnit.SECONDS);
}
public void every(String id, Runnable runnable, String interval) {
JobTrigger.every(interval).schedule(this, Job.multipleTimes(id, runnable, this));
}
public void every(Runnable runnable, String interval) {
JobTrigger.every(interval).schedule(this, Job.multipleTimes(runnable, this));
}
public void every(Runnable runnable, long interval, TimeUnit timeUnit) {
JobTrigger.every(interval, timeUnit).schedule(this, Job.multipleTimes(runnable, this));
}
public void every(String id, Runnable runnable, long interval, TimeUnit timeUnit) {
JobTrigger.every(interval, timeUnit).schedule(this, Job.multipleTimes(id, runnable, this));
}
public void fixedDelay(Runnable runnable, String interval) {
JobTrigger.every(interval).schedule(this, Job.multipleTimes(runnable, this));
}
public void fixedDelay(String id, Runnable runnable, String interval) {
JobTrigger.every(interval).schedule(this, Job.multipleTimes(id, runnable, this));
}
public void fixedDelay(Runnable runnable, long interval, TimeUnit timeUnit) {
JobTrigger.fixedDelay(interval, timeUnit).schedule(this, Job.multipleTimes(runnable, this));
}
public void fixedDelay(String id, Runnable runnable, long interval, TimeUnit timeUnit) {
JobTrigger.fixedDelay(interval, timeUnit).schedule(this, Job.multipleTimes(id, runnable, this));
}
private int parseTime(String timeDuration) {
if (timeDuration.startsWith("${") && timeDuration.endsWith("}")) {
timeDuration = app().config().get(timeDuration.substring(2, timeDuration.length() - 1));
}
return Time.parseDuration(timeDuration);
}
public void on(DateTime instant, Runnable runnable) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("schedule runnable[%s] on %s", runnable, instant);
}
DateTime now = DateTime.now();
E.illegalArgumentIf(instant.isBefore(now));
Seconds seconds = Seconds.secondsBetween(now, instant);
executor().schedule(wrap(runnable), seconds.getSeconds(), TimeUnit.SECONDS);
}
public <T> Future<T> on(DateTime instant, Callable<T> callable) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("schedule callable[%s] on %s", callable, instant);
}
DateTime now = DateTime.now();
E.illegalArgumentIf(instant.isBefore(now));
Seconds seconds = Seconds.secondsBetween(now, instant);
return executor().schedule(callable, seconds.getSeconds(), TimeUnit.SECONDS);
}
public void on(AppEventId appEvent, final Runnable runnable) {
on(appEvent, runnable, false);
}
public void on(AppEventId appEvent, final Runnable runnable, boolean runImmediatelyIfEventDispatched) {
on(appEvent, runnable.toString(), runnable, runImmediatelyIfEventDispatched);
}
public void post(AppEventId appEvent, final Runnable runnable) {
post(appEvent, runnable, false);
}
public void post(AppEventId appEvent, final Runnable runnable, boolean runImmediatelyIfEventDispatched) {
Job job = jobById(appEventJobId(appEvent));
if (null == job) {
processDelayedJob(wrap(runnable), runImmediatelyIfEventDispatched);
} else {
job.addFollowingJob(Job.once(runnable, this));
}
}
public void on(AppEventId appEvent, String jobId, final Runnable runnable) {
on(appEvent, jobId, runnable, false);
}
public void on(AppEventId appEvent, String jobId, final Runnable runnable, boolean runImmediatelyIfEventDispatched) {
boolean traceEnabled = LOGGER.isTraceEnabled();
if (traceEnabled) {
LOGGER.trace("binding job[%s] to app event: %s, run immediately if event dispatched: %s", jobId, appEvent, runImmediatelyIfEventDispatched);
}
Job job = jobById(appEventJobId(appEvent));
if (null == job) {
if (traceEnabled) {
LOGGER.trace("process delayed job: %s", jobId);
}
processDelayedJob(wrap(runnable), runImmediatelyIfEventDispatched);
} else {
if (traceEnabled) {
LOGGER.trace("schedule job: %s", jobId);
}
job.addPrecedenceJob(Job.once(jobId, runnable, this));
}
}
public void post(AppEventId appEvent, String jobId, final Runnable runnable) {
post(appEvent, jobId, runnable, false);
}
public void post(AppEventId appEvent, String jobId, final Runnable runnable, boolean runImmediatelyIfEventDispatched) {
Job job = jobById(appEventJobId(appEvent));
if (null == job) {
processDelayedJob(wrap(runnable), runImmediatelyIfEventDispatched);
} else {
job.addFollowingJob(Job.once(jobId, runnable, this));
}
}
public void alongWith(AppEventId appEvent, String jobId, final Runnable runnable) {
Job job = jobById(appEventJobId(appEvent));
if (null == job) {
processDelayedJob(wrap(runnable), false);
} else {
job.addParallelJob(Job.once(jobId, runnable, this));
}
}
private void processDelayedJob(final Runnable runnable, boolean runImmediatelyIfEventDispatched) {
if (runImmediatelyIfEventDispatched) {
try {
runnable.run();
} catch (Exception e) {
Act.LOGGER.error(e, "Error running job");
}
} else {
now(runnable);
}
}
/**
* Cancel a scheduled Job by ID
* @param jobId the job Id
*/
public void cancel(String jobId) {
Job job = jobById(jobId);
if (null != job) {
removeJob(job);
} else {
ScheduledFuture future = scheduled.remove(jobId);
if (null != future) {
future.cancel(true);
}
}
}
public void beforeAppStart(final Runnable runnable) {
on(AppEventId.START, runnable);
}
public void afterAppStart(final Runnable runnable) {
post(AppEventId.START, runnable);
}
public void beforeAppStop(final Runnable runnable) {
on(AppEventId.STOP, runnable);
}
public SimpleProgressGauge progressGauge(String jobId) {
return jobById(jobId).progress();
}
public void setJobProgressGauge(String jobId, ProgressGauge progressGauge) {
Job job = jobById(jobId);
if (null == job) {
LOGGER.warn("cannot find job by Id: " + jobId);
} else {
job.setProgressGauge(progressGauge);
}
}
C.List<Job> jobs() {
return C.list(jobs.values());
}
C.List<Job> virtualJobs() {
final AppJobManager jobManager = Act.jobManager();
return C.list(scheduled.entrySet()).map(new $.Transformer<Map.Entry<String, ScheduledFuture>, Job>() {
@Override
public Job transform(Map.Entry<String, ScheduledFuture> entry) {
return new Job(entry.getKey(), jobManager);
}
});
}
void futureScheduled(String id, ScheduledFuture future) {
scheduled.putIfAbsent(id, future);
}
Job jobById(String id) {
Job job = jobs.get(id);
if (null == job) {
ScheduledFuture future = scheduled.get(id);
if (null != future) {
return new Job(id, Act.jobManager());
}
Act.LOGGER.warn("cannot find job by id: %s", id);
}
return job;
}
void addJob(Job job) {
jobs.put(job.id(), job);
}
void removeJob(Job job) {
String id = job.id();
jobs.remove(id);
ScheduledFuture future = scheduled.remove(id);
if (null != future) {
future.cancel(true);
}
}
ScheduledThreadPoolExecutor executor() {
return executor;
}
private void initExecutor(App app) {
int poolSize = app.config().jobPoolSize();
executor = new ScheduledThreadPoolExecutor(poolSize, new AppThreadFactory("jobs"), new ThreadPoolExecutor.AbortPolicy());
executor.setRemoveOnCancelPolicy(true);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("init executor with thread pool: %s", poolSize);
}
}
private void createAppEventListener(AppEventId appEventId) {
String jobId = appEventJobId(appEventId);
Job job = new Job(jobId, this);
addJob(job);
app().eventBus().bind(appEventId, new _AppEventListener(jobId, job));
}
private static class _AppEventListener extends AppEventListenerBase {
private Runnable worker;
_AppEventListener(String id, Runnable worker) {
super(id);
this.worker = $.NPE(worker);
}
@Override
public void on(EventObject event) throws Exception {
worker.run();
}
@Override
protected void releaseResources() {
if (null != worker && worker instanceof Destroyable) {
((Destroyable) worker).destroy();
}
}
}
private Runnable wrap(Runnable runnable) {
return new ContextualJob(randomJobId(), runnable);
}
private Job wrap($.Function<ProgressGauge, ?> worker) {
return new ContextualJob(randomJobId(), worker);
}
private Runnable wrap(final Callable callable) {
return new Runnable() {
@Override
public void run() {
try {
callable.call();
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw E.unexpected(e);
}
}
};
}
private class ContextualJob extends Job {
private JobContext origin_ = JobContext.copy();
ContextualJob(String id, final Runnable runnable) {
super(id, AppJobManager.this, new $.F0() {
@Override
public Object apply() throws NotAppliedException, $.Break {
runnable.run();
return null;
}
}, true);
foo();
}
ContextualJob(String id, final $.Function<ProgressGauge, ?> worker) {
super(id, AppJobManager.this, worker);
foo();
}
@Override
protected void _before() {
// copy the JobContext of parent thread into the current thread
JobContext.init(origin_);
}
@Override
protected void _finally() {
JobContext.clear();
removeJob(this);
}
private void foo() {
app().eventBus().once(MailerContext.InitEvent.class, new OnceEventListenerBase<MailerContext.InitEvent>() {
@Override
public boolean tryHandle(MailerContext.InitEvent event) throws Exception {
MailerContext mailerContext = MailerContext.current();
if (null != mailerContext) {
_before();
return true;
}
return true;
}
});
}
}
private String randomJobId() {
return app().cuid() + S.random(4);
}
}