-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJobExecutor.java
64 lines (55 loc) · 1.98 KB
/
JobExecutor.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
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
/**
* Created with IntelliJ IDEA.
* User: WuYifei
* Date: 2017/2/8
* Time: 10:04
*/
public class JobExecutor {
private static final ExecutorService executor = ThreadPoolUtil.newCachedExecutor("light-job");
private static Logger logger = LoggerFactory.getLogger(JobExecutor.class);
public static void execute(final TimeoutJob timeoutJob) {
executor.execute(new Runnable() {
public void run() {
try {
timeoutJob.run();
} catch (JobException e) {
logger.error(e.getMessage(), e);
}
}
});
}
public static JobResult executeWithResult(final TimeoutJob timeoutJob) {
Future<JobResult> future = executor.submit(new Callable<JobResult>() {
public JobResult call() throws Exception {
timeoutJob.run();
return new JobResult(JobResult.RETURN_SUCCESS, "job run success");
}
});
try {
return future.get();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new JobResult(JobResult.RETURN_FAIL, e.getMessage());
}
}
public static <T> void executeInCurrentThread(CurrentThreadJob<T> currentThreadJob) throws JobException {
if (JobPool.getInstance().add(currentThreadJob)) {
try {
currentThreadJob.run();
} finally {
JobPool.getInstance().remove(currentThreadJob);
}
} else {
//not occur
logger.warn("currentThread is executing the job, not occur");
}
}
public static <X> Future<X> execute(Callable<X> callable) {
return executor.submit(callable);
}
}