gpt4 book ai didi

java - 如何同步 jBatch 执行?

转载 作者:行者123 更新时间:2023-12-03 22:56:29 25 4
gpt4 key购买 nike

我正在用 jBeret 编写一个 jBatch 程序。我目前就是这样做的。

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);

还有其他方法吗?

最佳答案

如果您需要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);
}
}

关于java - 如何同步 jBatch 执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32493463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com