Zeitsynchronisation von Zend_Date mittels Zend_TimeSync und mehrerer TimeserverSynchronizing Zend_Date using Zend_TimeSync and multiple time servers

This post describes a simple approach to implement time synchronization using Zend_TimeSync for Zend_Date using multiple time servers.

First of all you will need to create a new Zend_TimeSync instance, specifying a list of possible time servers. You may use the server pool provided by ntp.org for this purpose. In case you specifiy multiple servers (which generally is a good idea for fallback reasons, etc.), the ZF manual advises to name these servers individually in order to be able to refer to them by name later on. Following is an excerpt from application.ini file specifying the list of available time servers, ordered by preference.

timeservers.ntp.generic = "0.europe.pool.ntp.org"
timeservers.ntp.fallback = "1.europe.pool.ntp.org"
timeservers.ntp.reserve = "2.europe.pool.ntp.org"
timeservers.ntp.additional = "3.europe.pool.ntp.org"

Note that the default protocol used by Zend_TimeSync is NTP. In order to specifiy a different protocol please refer to the ZF manual: http://framework.zend.com/manual/en/zend.timesync.working.html.

Once the list of available time servers has been defined it is time to setup Zend_TimeSync to use it:

$timeserverConfig = $this->getOption('timeservers); //get options from application.ini
$timeservers = new Zend_TimeSync($timeservers['ntp']); //use "named" timeservers

Note that I have kept the time server naming schema as shown in ZF manual.

The next step is to configure Zend_Date to use a primary time server from this list. Hereby, Zend_Date accepts a single timeserver using the timesync option, as shown in the following code snippet:

Zend_Date::setOptions(array(
  'timesync' => $timeSyncServers->getServer()));

This means that once the current time server is set (using a call to getDate() on the Zend_TimeSync instance) Zend_Date‘s timesync option can be successfully specified.

As setting up Zend_Date with the correct time server is a repetitive task, it is best and easiest to put this code into your bootstrap file.

The following piece of code shows the complete initialisation of Zend_Date using Zend_TimeSync and multiple time servers based on the NTP protocol:

protected function _initDate() {
  try {
    $timeServers = $this->getOption('timeservers');
    $timeSyncServers = new Zend_TimeSync($timeServers['ntp']);

    if (!$timeSyncServers->getDate()) {
      throw new Zend_TimeSync_Exception('Failed to get date from current time server');
    }

    Zend_Date::setOptions(array(
      'timesync' => $timeSyncServers->getServer()));
  } catch (Zend_TimeSync_Exception $e) {
      // handle error...
  }
}

Note that it is good practice for bigger projects to setup caching for Zend_Date to improve performance, but this is a topic for another post 🙂

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *