java - 回滚时取消 ejb 定时器

标签 java jakarta-ee timer jboss7.x ejb-3.1

有没有办法确保在发生异常时取消周期性(每 10 秒)和持久性计时器? @Timeout 方法的实现是这样的(从遗留代码中简化而来):

@Timeout
@TransactionAttribute(REQUIRES_NEW)
public void onTimeout(Timer timer) {
    try {
        doSomeBusinessLogic();
    } catch (Exception e) {
        // throwing this exception makes sure rollback is triggered
        throw new EJBException(e);
    }
}

doSomeBusinessLogic() 发生任何异常时,需要回滚其事务。这工作正常。但是,我还要确保取消计时器。

直接的解决方案是将 timer.cancel() 放在 catch block 中。然而,这是行不通的,因为取消也会被回滚(JEE6 Turorial):

An enterprise bean usually creates a timer within a transaction. If this transaction is rolled back, the timer creation also is rolled back. Similarly, if a bean cancels a timer within a transaction that gets rolled back, the timer cancellation is rolled back. In this case, the timer’s duration is reset as if the cancellation had never occurred.

如果发生异常/回滚,我如何确保取消计时器(防止任何进一步的超时)?设置最大重试次数也足够了,但我认为 JBoss 不支持这一点。

应用服务器是JBoss AS 7.2。

最佳答案

我也尝试了 Sergey 提出的解决方案,它似乎有效 - 计时器被取消。在 JBoss EAP 6.2 上测试。 这是我用于测试的代码:

@Stateless
public class TimeoutTest implements TimeoutTestLocal {

@Resource
TimerService timerService;

@Resource
SessionContext sessionContext;

@Timeout
@TransactionAttribute(TransactionAttributeType.NEVER)
public void tmout(javax.ejb.Timer timer) {
    try {
        System.out.println("timout invoked");
        //instead of internal call let's invoke doNothing as
        //this timeout callback is client of TimeoutTest EJB
        //in this way doNothing will be run inside transaction
        TimeoutTestLocal local = sessionContext.getBusinessObject(TimeoutTestLocal.class);
        local.doNothing();  
    } catch (Exception e) {
        timer.cancel();
        System.out.println("Timer cancelled");
    }
}

@Override 
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void doNothing() {
    throw new EJBException("RE Exception");
}


@Override
public void schedule() {
    timerService.createTimer(5000, 10000, "test");
}
}

关于java - 回滚时取消 ejb 定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26973933/

相关文章:

java - 从适配器中的模型传输日期格式

java - Jscape 简历上传

java - 在 Weblogic Server 中设置 Java 堆空间

java - Glassfish:在部署期间修改 EAR 的部署描述符

java - 整个应用程序是否有一个 onPause ?

java - 以这种方式找到排列的复杂性是什么?

java - 如何在工作流程步骤中访问 Assets

c# - 如何在c#中设置定时器在特定时间执行

PowerShell显示耗时

java - Olingo (OData 4) 如何为entityType创建注释?