我正在使用 EJB 计时器,但是在尝试在同一个项目中同时运行计时器和持久实体时遇到了麻烦。在我的初始设置中,我只有计时器,并且这些计时器按预期触发:
@Stateless
public class TimerHandler {
@Resource
protected TimerService mTimerService;
@PostConstruct
public void init() {
// could do cool stuff but choose not to
}
public Timer start(long aDuration) {
TimerConfig conf = new TimerConfig();
conf.setPersistent(false); // don't want the timer to be saved
return mTimerService.createSingleActionTimer(aDuration, conf);
}
@Timeout
public void timeOutAction(Timer aTimer) {
// does fancy stuff
System.out.println("So fancy :)");
}
}
我在让计时器运行时遇到了一些麻烦,但我采用了蛮力的方式并重新安装了 Payara (Glassfish)。在此之后使用计时器很好。我可以这样开始和取消它:
@Stateful
public class MyClass {
@EJB
private TimerHandler mTimerHandler;
private Timer mTimer;
public void startTimer(int aDuration) {
mTimer = mTimerHandler.start(aDuration);
}
public void stopTimer() {
try {
mTimer.cancel();
} catch (NoSuchObjectLocalException | NullPointerException ex) {
System.out.println("There is no timer running.");
}
}
}
但是,在我尝试将实体添加到我的项目后,问题就出现了。我的实体如下所示:
@Entity
public class TestEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String testValue;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTestValue() {
return testValue;
}
public void setTestValue(String value) {
testValue = value;
}
// removed standard code for @Override of equals(),
// hashCode() & toString()
}
我通过我的控制器 bean 操作:
@Stateless
public class TestDBController {
@PersistenceContext(unitName = "TimerTestWithDBPU")
private EntityManager em;
public long saveValue(String value) {
TestEntity entity = new TestEntity();
entity.setTestValue(value);
em.persist(entity);
em.flush();
return entity.getId();
}
public String getValue(long aId) {
TestEntity entity = em.find(TestEntity.class, aId);
return entity.getTestValue();
}
}
并且我通过以下方式设置了我的持久性单元(persistence.xml):
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="TimerTestWithDBPU" transaction-type="JTA">
<jta-data-source>jdbc/timer_test_pool</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action"
value="create"/>
</properties>
</persistence-unit>
</persistence>
添加此实体和持久性单元后,我收到以下错误:
EJB Timer Service is not available.
Timers for application with id [XYZ] will not be deleted
为什么是这样?您不能同时使用 ejb 计时器和持久实体运行应用程序吗?