Application servers and database servers are often located on different machines. If you are not using a Network Time Protocol (NTP) service, the clocks on different servers in your deployment may be not be synchronized. Even if they are synchronized manually, clocks may "drift" over time. This can cause application errors when data is saved on one server then retrieved by another with a different clock time. Since all application servers must persist data to the same database, the database server’s time should be used when calculating timestamps. This ensures consistency across all servers in the deployment and reduces the likelihood of errors due to time conflicts.
For this reason, the
getCurrentTime() method provided by the
timeService bean should always be used whenever a timestamp is required.
Date timestamp = timeService.getCurrentTime();
How it works
The time service bean queries the database for its internal timestamp. It calculates the difference between the database timestamp and the server’s clock time. When the time service’s
getCurrentTime() method is called, a timestamp is calculated by adding the difference to the application server timestamp, which is approximately equal to the database server time.
The bean periodically re-query the database server for its timestamp to sync up any time drift between the servers. The query interval can be adjusted by changing the
cacheTimeout property of the time service bean.
timeService bean is defined in
service.xml as follows:
<bean id="timeService" parent="txProxyTemplate"> <property name="target"> <bean class="com.elasticpath.service.misc.impl.CachedSyncingServerTimeServiceImpl"> <property name="wrappedTimeService" ref="databaseTimeService"/> <!-- Default time between sync is 30 minutes --> <property name="cacheTimeout" value="1800000" /> </bean> </property> </bean> <bean id="databaseTimeService" class="com.elasticpath.service.misc.impl.DatabaseServerTimeServiceImpl"> <property name="elasticPath"> <ref bean="elasticPath" /> </property> <property name="persistenceEngine"> <ref bean="persistenceEngine"/> </property> </bean>