Previous Next

Working with Zend_TimeSync

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

Note:

All examples in this chapter use a public, generic time server: 0.europe.pool.ntp.org. You should use a public, generic time server which is close to your application server. See » http://www.pool.ntp.org for information.

Generic Time Server Request

Requesting the time from a time server is simple. First, you provide the time server from which you want to request the time.

$server = new Zend_TimeSync('0.pool.ntp.org');

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

So what is happening in the background of Zend_TimeSync? First the syntax of the time server is checked. In our example, '0.pool.ntp.org' is checked and recognised as a possible address for a time server. Then when calling getDate() the actual set time server is requested and it will return its 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 correct time.

For details about Zend_Date and its methods see the Zend_Date documentation.

Multiple Time Servers

Not all time servers are always available to return their time. Servers may be unavailable during maintenance, for example. When the time cannot be requested from the time server, you will get an exception.

Zend_TimeSync is a simple solution that can handle multiple time servers and supports an automatic fallback mechanism. There are two supported ways; you can either specify an array of time servers when creating the instance, or you can add additional time servers to the instance using the addServer() method.

$server = new Zend_TimeSync(array('0.pool.ntp.org',
                                  '1.pool.ntp.org',
                                  '2.pool.ntp.org'));
$server->addServer('3.pool.ntp.org');

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

There is no limit to the number of time servers you can add. When a time server can not be reached, Zend_TimeSync will fallback and try to connect to the next time server.

When you supply more than one time server- which is considered a best practice for Zend_TimeSync- you should name each server. You can name your servers with array keys, with the second parameter at instantiation, or with the second parameter when adding another time server.

$server = new Zend_TimeSync(array('generic'  => '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 time servers allows you to request a specific time server as we will see later in this chapter.

Protocols of Time Servers

There are different types of time servers. Most public time servers use the NTP protocol. But there are other time synchronization protocols available.

You set the proper protocol in the address of the time server. There are two protocols which are supported by Zend_TimeSync: NTP and SNTP. The default protocol is NTP. If you are using NTP, you can omit the protocol in the address as demonstrated in the previous examples.

$server = new Zend_TimeSync(array('generic'  => '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 can handle mixed time servers. So you are not restricted to only one protocol; you can add any server independently from its protocol.

Using Ports for Time Servers

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

But sometimes the port that the protocols use differs 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 after the address. If no port is defined, then Zend_TimeSync will use the standard port.

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

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

Time Servers Options

There is only one option within Zend_TimeSync which will be used internally: timeout. You can set any self-defined option you are in need of and request it, however.

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 time server if the requested time server does not respond in one second.

With the setOptions() method, you can set any option. This function accepts an array where the key is the option to set and the value is the value of that option. Any previously 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 specified, or, if no key is set, it will return all set options.

Zend_TimeSync::setOptions(array('timeout' => 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. Each instance of Zend_TimeSync will use the same options.

Using Different Time Servers

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

$server = new Zend_TimeSync(array('generic'  => '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');

Information from Time Servers

Time servers not only offer the time itself, but also additional information. You can get this information with the getInfo() method.

$server = new Zend_TimeSync(array('generic'  => 'ntp:\\0.pool.ntp.org',
                                  'fallback' => 'ntp:\\1.pool.ntp.org'));

print_r ($server->getInfo());

The returned information differs with the protocol used and can also differ with the server used.

Handling Exceptions

Exceptions are collected for all time servers and returned as an array. So you can iterate through all thrown exceptions as shown in the following example:

$serverlist = array(
        // invalid servers
        'invalid_a'  => '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 Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
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_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
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
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
Filters for Zend_File_Transfer
Migrating from previous versions
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
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
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
Advanced Usage of Zend_Json
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
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
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_Navigation
Introduction
Pages
Containers
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 PDF Documents
Working with Pages
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
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_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Stroage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
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_Twitter
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
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Zend_Tool_Project
Zend_Tool_Project Introduction
Create A Project
Zend Tool Project Providers
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Migrating from Previous Versions
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
Introduction
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information