In this example, we will learn how to use Poll component to make ajax calls periodically.
<h:form> CPU usage: <b> <h:outputText id="cpu_usage" value="#{cpuUsageBean.cpuUsage} %"/> </b> <p:poll interval="1" update="cpu_usage"/> </h:form>
@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
Dependencies and Technologies Used: