Action Poller in Visualfoce Page

According to SF documentation, It is

A timer that sends an AJAX request to the server according to a time interval that you specify. Each request can result in a full or partial page update.

Examples :

  1. After certain amount of time, you want to perform specific event.
  2. From Apex if you want to get continuous status of batch and then you want to execute specific task.
  3. If you want to split transactions for doing multiple activities.

Document from salesforce is here.

Let’s understand this by below example.

We will print the Booking Status. This sample page will poll the server for getting current status while displaying the specific message “Booking Your Tickets…” when action poller executes.

When the status changed to Booked we want to terminate the action poller.

Live demo available here.

Apex Class :

public with sharing class BookingPollerContrl { // the payment statuses 
    public List < String > statuses = new List < String > {
        'Connecting to IRCTC',
        'Authorising',
        'Authorised',
        'Booked'
    };
    // the index of the current Status 
    private Integer currentStatusIdx = 0; // getter to retrieve the current Status 
    public String getBookingStatus() {
        return statuses[currentStatusIdx];
    }
    // action method invoked by the poller - increments the 
    // current Status index 
    public PageReference changeBookingStatus() {
        currentStatusIdx++;
        return null;
    }
}

Visualforce Page :

<apex:page controller="BookingPollerContrl">
   <apex:sectionHeader title="Booking Window" />
   <apex:pageBlock title="Status">
      <apex:form >
         <!-- the poller - turned off when the Booking Status becomes 'Booked' --> 
         <apex:actionPoller action="{!changeBookingStatus}" rerender="bookingStatus" interval="5" status="status" enabled="{!BookingStatus!='Booked'}"/>
         <apex:outputPanel id="bookingStatus">
            The status of your Booking is : 
            <apex:outputText style="font-weight: bold" value=" {!BookingStatus}"/>
         </apex:outputPanel>
         <br/> 
         <hr/>
         <apex:actionStatus startText="Booking Your Tickets..." id="status"/>
      </apex:form>
   </apex:pageBlock>
</apex:page>