0

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

Matt Vegas
  • 453
  • 5
  • 17

1 Answers1

0

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#############
Matt Vegas
  • 453
  • 5
  • 17
  • Remember to set @ManagedBean(eager= true, if you want to init the bean during server startup, if not the init method will be called on the first call – Matt Vegas Jul 12 '18 at 10:07
  • I didn't understand why someone vote as negative this solution, please let me understand why this solution that is working fine is not correct. – Matt Vegas Jul 13 '18 at 07:41