Previous Next

Working with Zend_TimeSync

Zend_TimeSync can return the actual time from any given NTP or SNTP timeserver. It can automatically handle multiple servers and provides a simple interface.

Note:

In all examples within this chapter we are using one of the available public generic timeservers. In our case 0.europe.pool.ntp.org. For your environment it is recommended that you are using a public generic timeserver which is nearly to the location of your server. See » http://www.pool.ntp.org for details.

Generic timeserver request

Requesting the time from a timeserver is quite simple. All you have to give is the timeserver from which you want to have the time.

getDate()->getIso();

So what is happening in the background of Zend_TimeSync? First the syntax of the given server is checked. So in our example '0.pool.ntp.org' is checked and recognised as possible correct adress for a timeserver. Then when calling getDate() the actual set timeserver is requested and it will return it's own time. Zend_TimeSync then calculates the difference to the actual time of the server running the script and returns a Zend_Date object with the actual, corrected time.

For details about Zend_Date and it's methods you can refer to Zend_Date.

Multiple timeservers

Not all timeservers are always available and will return their time. Servers will have a time where they can not be reached, for example when having a maintenance. In such cases, when the time can not be requested from the timeserver, you would get an exception.

As simple solution Zend_TimeSync can handle multiple timeservers and supports a automatic fallback machanism. There are two supported ways. You can either give an array of timeservers when creating the instance. Or you can add additionally timeservers afterwards with the addServer() method.

addServer('3.pool.ntp.org');

print $server->getDate()->getIso();

There is no limitation in the ammount of timeservers you can add. When a timeserver can not be reached Zend_TimeSync will fallback and try to connect to the next given timeserver.

When you give more than one timeserver, which should be your default behaviour, you should name your servers. You can either name your servers with the array key, but also with the second parameter at initiation or addition of an other timeserver.

 '0.pool.ntp.org',
                                  'fallback' => '1.pool.ntp.org',
                                  'reserve'  => '2.pool.ntp.org'));
$server->addServer('3.pool.ntp.org', 'additional');

print $server->getDate()->getIso();

Naming the timeservers gives you the ability to request a specific timeserver as we will see later in this chapter.

Protocols of timeservers

There are different types of timeservers. The most public timeservers are using NTP as protocol. But there are different other protocols available.

You can set the proper protocol within the address of the timeserver. Actual there are two protocols which are supported by Zend_TimeSync. The default protocol is NTP. If you are only using NTP you can ommit the protocol within the address as show in the previous examples.

 'ntp:\\0.pool.ntp.org',
                                  'fallback' => 'ntp:\\1.pool.ntp.org',
                                  'reserve'  => 'ntp:\\2.pool.ntp.org'));
$server->addServer('sntp:\\internal.myserver.com', 'additional');

print $server->getDate()->getIso();

Zend_TimeSync is able to handle mixed timeservers. So you are not restricted to only one protocol, but you can add any server independently from it's protocol.

Using ports for timeservers

As every protocol within the world wide web, the NTP and SNTP protocols are using standard ports. NTP uses port 123 and SNTP uses 37.

But sometimes the used port differ from the standard one. You can define the port which has to be used for each server within the address. Just add the number of the port behind the address. If no port is defined, then Zend_TimeSync will use the standard port.

 'ntp:\\0.pool.ntp.org:200',
                                  'fallback' => 'ntp:\\1.pool.ntp.org'));
$server->addServer('sntp:\\internal.myserver.com:399', 'additional');

print $server->getDate()->getIso();

Options for timeservers

Actually there is only one option within Zend_TimeSync which will be used internally. But you can set any self defined option you are in need for and request it.

The option timeout defines the number of seconds after which a connection is detected as broken when there was no response. The default value is 1, which means that Zend_TimeSync will fallback to the next timeserver is the actual requested timeserver does not respond in one second.

With the setOptions() method, you can set any option. It accepts an array where the key is the option to set and the value is the value of that option. Any previous set option will be overwritten by the new value. If you want to know which options are set, use the getOptions() method. It accepts either a key which returns the given option if set or, if no key is set, it will return all set options.

 3, 'myoption' => 'timesync'));
$server = new Zend_TimeSync(array('generic'  => 'ntp:\\0.pool.ntp.org',
                                  'fallback' => 'ntp:\\1.pool.ntp.org'));
$server->addServer('sntp:\\internal.myserver.com', 'additional');

print $server->getDate()->getIso();
print_r(Zend_TimeSync::getOptions();
print "Timeout = " . Zend_TimeSync::getOptions('timeout');

As you can see the options for Zend_TimeSync are static, which means that each instance of Zend_TimeSync will act with the same options.

Using different timeservers

The default behaviour for requesting a time is to request it from the first given server. But sometimes it is useful to set a different timeserver from which to request the time. This can be done with the setServer() method. To define the used timeserver just set the alias as parameter within the method. And to get the actual used timeserver just call the getServer() method. It accepts an alias as parameter which defined the timeserver to be returned. If no parameter is given, the current timeserver will be returned.

 'ntp:\\0.pool.ntp.org',
                                  'fallback' => 'ntp:\\1.pool.ntp.org'));
$server->addServer('sntp:\\internal.myserver.com', 'additional');

$actual = $server->getServer();
$server = $server->setServer('additional');

Informations from timeservers

Timeservers offer not only the time itself but also additionally informations. You can get these informations with the getInfo() method.

 'ntp:\\0.pool.ntp.org',
                                  'fallback' => 'ntp:\\1.pool.ntp.org'));

print_r ($server->getInfo());

The returned informations differ with the used protocols and they can also differ with the used servers.

Taking care of exceptions

Exceptions are collected for all timeserver and will be returned as array. So you are able to iterate through all throwed exceptions like shown in the following example:

 'ntp://a.foo.bar.org',
        'invalid_b'  => 'sntp://b.foo.bar.org',
);

$server = new Zend_TimeSync($serverlist);

try {
    $result = $server->getDate();
    echo $result->getIso();
} catch (Zend_TimeSync_Exception $e) {

    $exceptions = $e->get();

    foreach ($exceptions as $key => $myException) {
        echo $myException->getMessage();
        echo '
'; } }
Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Use
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The theory of caching
Zend_Cache frontends
Zend_Cache backends
Zend_Captcha
Introduction
Captcha Operation
Captcha Adapters
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Console_Getopt
Introduction to Getopt
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router: Zend_Controller_Router_Rewrite
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to work with currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of dates
Constants for General Date Functions
Working examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction to Gdata
Authenticating with AuthSub
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using the YouTube Data API
Using Picasa Web Albums
Catching Gdata Exceptions
Zend_Http
Zend_Http_Client - Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
JSON Objects
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
Zend_Loader
Loading Files and Classes Dynamically
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported Languages for Locales
Supported Regions for Locales
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction.
Creating and loading PDF documents.
Save changes to the PDF document.
Document pages.
Drawing.
Document Info and Metadata.
Zend_Pdf module usage example.
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery. Introduction
Class autodiscovering.
Functions autodiscovering.
Autodiscovering. Datatypes.
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Zend_Version
Reading the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
PHP Version
PHP Extensions
Zend Framework Components
Zend Framework Dependencies
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Copyright Information