Marcin Marczyk
Marcin Marczyk

Reputation: 93

Dynamically change timeout interval in Timer

I need to make an app as below. Changing a value in web app's input will change refresh interval in Timer. It needs to be dynamically, is it possible to do with Timer?

Upvotes: 2

Views: 3096

Answers (2)

Aksel Willgert
Aksel Willgert

Reputation: 11537

Use the TimerService in an ejb. In this example any previous timer with a given name is canceled before initiating the new timer with new intervall

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

@Stateless
public class TimerBean {
    @Resource
    protected TimerService timerService;

    @Timeout
    public void timeoutHandler(Timer timer) {
        String name = timer.getInfo().toString();
        System.out.println("Timer name=" + name);
    }

    public void startOrModifyTimer(long initialExpiration, long interval, String name){      
        //Cancel previous timer
        Collection<Timer> timers = timerService.getAllTimers();
        for (Timer timer: timers) {
            if (timer.getInfo().equals(name)) {
                timer.cancel();
            }
        }

        TimerConfig config = new TimerConfig();
        config.setInfo(name);
        config.setPersistent(false);
        timerService.createIntervalTimer(initialExpiration, interval, config);
    }
}

Upvotes: 2

Gabriel Aramburu
Gabriel Aramburu

Reputation: 2981

Once created a EJB Timer cannot change the interval period configured (at least it's not provided by ejb specification). You can instead cancel the original one and create a new one with a different interval.

Upvotes: 3

Related Questions