【发布时间】:2021-04-26 12:34:27
【问题描述】:
我正在尝试开发一个以特定间隔运行并执行一些数据库修改的类。
我设法以特定时间间隔运行的代码,从数据库中检索记录,但是当我想提交对数据库的更改时,我收到以下错误。
WFLYEE0110: Failed to run scheduled task: javax.persistence.TransactionRequiredException: WFLYJPA0060: Transaction is required to perform this operation (either use a transaction or extended persistence context)
是否允许@ApplicationScoped 创建事务?
谢谢!
@ApplicationScoped
@ActivateRequestContext
public class TaskRunner {
@PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager em;
@Resource private ManagedScheduledExecutorService scheduler;
private ScheduledFuture<?> TaskRunnerScheduler;
private boolean initialized = false;
private void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
if (initialized) return;
initialized = true;
try {
// Execute at startup
TaskRunner = scheduler.schedule(this::runSchedule, getSchedule());
} catch (Throwable throwable) {
}
}
@Transactional
private void runSchedule() {
//retrieve db records
//make changes and commit
//sample
//em.persist(someEntity)
}
private Trigger getSchedule() {
return new Trigger() {
@Override
public Date getNextRunTime(LastExecution lastExecutionInfo, Date taskScheduledTime) {
return Date.from(
ZonedDateTime.now().withSecond(0).withNano(0).plusHours("4").toInstant());
}
@Override
public boolean skipRun(LastExecution lastExecutionInfo, Date scheduledRunTime)
{return false;}};
}
}
【问题讨论】:
标签: jpa cdi entitymanager java-ee-8