user3362334
user3362334

Reputation: 2180

Cancel timer in lifecycle callback of singleton bean

I have an Java EE project running Wildfly 10.1 Final.

I am creating some timers programmatically using javax.ejb.TimerService like this:

timerService.createTimer(new Date(), null);

And now, I am trying to cancel those timers the next time the project is deployed, because they are still there every time I re-deploy the project, or restart the server.

I tried to use a Singleton Startup bean for that, like this:

@Startup
@Singleton
public class TimerKiller {

    @PostConstruct
    public void killTimers() {
        timerService.getAllTimers().forEach(timer -> timer.cancel());
    }

    @Resource
    TimerService timerService;
}

But, I get an exception:

java.lang.IllegalStateException: WFLYEJB0325: Cannot invoke timer service methods in lifecycle callback of non-singleton beans

This is the last exception in the stack trace (the last Caused By).

I can't seem to understand what does this mean. I tried googling but nothing comes up.

Upvotes: 2

Views: 570

Answers (1)

Georg Leber
Georg Leber

Reputation: 3605

Did you use javax.ejb.Singleton or javax.inject.Singleton. Make sure you are using javax.ejb.Singleton.

You can also use a e.g. SingleActionTimer and specify it as non-persistent:

TimerConfig tc = new TimerConfig(null, false);
timerService.createSingleActionTimer(new Date(), tc);

Upvotes: 2

Related Questions