Time for action – manually start and stop polling
We will now demonstrate how to start and stop polling using external triggers such as start and stop buttons using following steps:
- Create a form with a poll component and start/stop buttons to start and stop polling using following code:
<h:form> <p:outputLabel value="Current Time:" /> <p:outputLabel id="currentTime" value="#{serverTimeBean.time}"/> <p:poll interval="1" listener="#{serverTimeBean.updateTime()}" update="currentTime" widgetVar="currentTimePoller" autoStart="false"/> <br/> <p:button value="Start" onclick="currentTimePoller.start()" href="#" /> <p:button value="Stop" onclick="currentTimePoller.stop()" href="#"/><br/> </h:form>
What just happened?
We have set the autoStart
attribute to false, so that polling does not start automatically on page load. We have given a name for the poll component using widgetVar ="currentTimePoller"
so that we can invoke start()
and stop()
methods on the poll component. We have associated the start()
and stop()
methods to the button's onclick
events. So when we click on the Start button, polling will start and when we click on the Stop button, polling will be stopped.
Tip
PrimeFaces provides PrimeFaces push, which is better suitable for asynchronous processing. Prefer using PrimeFaces push over <p:poll>
component. For more information see http://www.primefaces.org/showcase/push/index.jsf.