Search code examples
javajsf-2javabeans

Refresh automatically on server side an ApplicationScoped Bean


I would like to refresh an ApplicationScoped Bean after 1h automatically invoking the init() method.

From client side, I can create a button to update the bean, but I would like to have it reloaded automatically every specific hour without clicking or waiting on a page(so no Ajax callback).

Moreover I read this article: Refresh/Reload Application scope managed bean but I would like to avoid to manage thread and so on.

Is it possible to implement without changing the Scope of the bean?

Thanks


Solution

  • I resolved implementing in this way:

    1) adding the Runnable implementation

    @ManagedBean(eager= true, name="dashboardbean")
    @ApplicationScoped
    public class DashboardBean implements Serializable, Runnable {
    

    2) adding implementation method "run"

    @Override
    public void run() {
        System.out.println("##########populateData#############");
        allServerCount = numbersServer.get("serverCount");
        System.out.println("###########server "+allServerCount+"#############");
        System.out.println("###########end populateData#############");
    }
    

    3) implemented the init method of the bean

    @PostConstruct
    public void init() {
        System.out.println("##########init#############");
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(this, 0, 2, TimeUnit.MINUTES);
        System.out.println("##########end#############");
    }
    

    4) adding part for destroing scheduler

    private ScheduledExecutorService scheduler; 
    
    @PreDestroy
    public void destroy() {
        scheduler.shutdownNow();
    }
    

    and this is the output generated every 2 minutes on the logs

    ##########populateData#############
    ###########server 339#############
    ###########end populateData#############
    ##########populateData#############
    ###########server 340#############
    ###########end populateData#############
    ##########populateData#############
    ###########server 340#############
    ###########end populateData#############