I am trying to develop a class that runs at specific intervals and performs some DB modifications.
the code I have managed to run at a specific interval, retrieve records from the DB, but when I want to commit changes to the DB I get the following error.
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)
is @ApplicationScoped allowed to create transactions?
Thanks!
@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;}};
}
}
question from:https://stackoverflow.com/questions/65838443/transaction-is-required-to-perform-this-operation-either-use-a-transaction-or-e