我正在用jBatch编写一个jBeret程序。我现在是这样做的。
final JobOperator operator = BatchRuntime.getJobOperator();
logger.debug("operator: {}", operator);
final long id = operator.start("some", null);
logger.debug("id: {}", id);
final JobExecution execution = operator.getJobExecution(id);
logger.debug("execution: {}", execution);问题是执行似乎是异步运行的,主方法只是返回。
我能做的最好是循环,直到退出状态为非空。
String status;
while ((status = execution.getExitStatus()) == null) {
//logger.debug("sleeping");
Thread.sleep(1000L);
}
logger.debug("status: {}", status);还有别的办法吗?
发布于 2015-09-15 12:28:30
如果您需要block-and-wait (正如您已经描述的那样),则没有其他选项,而是有类似于awaiCompletion()的实现。
您的循环方法可以改进。让我们以ThreadPoolExecutor为例。它有以下方法:
/**
* Blocks until all tasks have completed execution after a shutdown
* request, or the timeout occurs, or the current thread is
* interrupted, whichever happens first.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return {@code true} if this executor terminated and
* {@code false} if the timeout elapsed before termination
* @throws InterruptedException if interrupted while waiting
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;以下是实施情况:
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (;;) {
if (runStateAtLeast(ctl.get(), TERMINATED))
return true;
if (nanos <= 0)
return false;
nanos = termination.awaitNanos(nanos);
}
} finally {
mainLock.unlock();
}
}请注意:
因此,这里有一个经过改编的版本:
public static boolean awaitTermination(JobExecution execution, long timeout) throws InterruptedException {
final long limit = System.currentTimeMillis() + timeout;
for (;;) {
if (null != execution.getExitStatus()) {
return true;
}
if (System.currentTimeMillis() >= limit) {
return false;
}
Thread.sleep(timeout/10);
}
}发布于 2016-09-26 22:39:11
JBeret有一个内部方法:
org.jberet.runtime.JobExecutionImpl#awaitTermination(long timeout, TimeUnit timeUnit);为了这个目的。
在使用JBeret运行时,可以在从作业开始时获得的JobExecution上调用该方法。
发布于 2015-09-15 11:38:15
您可以实现JobListener类,也可以只扩展AbstractJobListener
...
public class MyJobListener extends AbstractJobListenerJobListener {
// The afterJob method receives control after the job execution ends.
@Override
public void afterJob() throws Exception { ... }
...
}在afterJob方法中,您可以使用一些基本的Java同步技术(未来)。
https://stackoverflow.com/questions/32493463
复制相似问题