Close

PrimeFaces - Ajax Poll Example

[Last Updated: Jan 5, 2019]

In this example, we will learn how to use Poll component to make ajax calls periodically.

JSF page

src/main/webapp/index.xhtml

<h:form>
    CPU usage:
    <b>
        <h:outputText id="cpu_usage" value="#{cpuUsageBean.cpuUsage} %"/>
    </b>
    <p:poll interval="1" update="cpu_usage"/>
</h:form>

The managed bean

@ManagedBean
@ViewScoped
public class CpuUsageBean {
  private AtomicInteger cpuUsage;

  @PostConstruct
  public void init() {
      cpuUsage = new AtomicInteger(50);
      ExecutorService es = Executors.newFixedThreadPool(1);
      es.execute(() -> {
          while (true) {
              //simulating cpu usage
              int i = ThreadLocalRandom.current()
                                       .nextInt(-10, 11);
              int usage = cpuUsage.get();
              usage += i;
              if (usage < 0) {
                  usage = 0;
              }
              else if(usage>100){
                  usage = 100;
              }
              cpuUsage.set(usage);
              try {
                  TimeUnit.MILLISECONDS.sleep(500);
              } catch (InterruptedException e) {
              }
          }
      });
  }

  public int getCpuUsage() {
      return cpuUsage.get();
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Example Project

Dependencies and Technologies Used:

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • JDK 1.8
  • Maven 3.3.9

PrimeFaces Ajax Poll Example Select All Download
  • ajax-poll-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also