On time
Archive - Originally posted on "The Horse's Mouth" - 2011-01-23 12:08:39 - Graham Ellis
Where financial transaction, bid sites, and some other web sites / actions are concerned, every second - and fraction of a second - matters, and the Network Time Protocol (NTP) exists to take the time on central atomic clocks and share it with other servers, which in turn share it onwards. But there's an awful lot more to that than you might anticipate; to get the time setting as accurate as possible, a conversation back and forth to each server to work out the lag time (time for data to travel) is needed, and indeed it's worth a machine that's being set up checking with several servers, rejecting any which are in spectacular disagreement, and setting itself based on the result. The home page of NTP is [here].
The clock on one of our dedicated servers "drifts". Set it right, and it's a few seconds in error by the end of the day (not a problem), a minute or two by the end of a fortnight (no big issue) and perhaps 10 or 15 minutes out after a couple of months. By the time it's got to that level, messages back and forth between our team are getting mistimed, it looks as if staff are clocking in late, and the synchronization between data on that system and the shared server that we use elsewhere for backup and various other purposes is getting flaky. So we need to reset / adjust every so often.
NTP? Surprisingly, no. We're behind a firewall and have to play with port 123 on that / get it changed if we want to use NTP. NTP has a baffling array of configurations available which are solving a fine accuracy issue which isn't an issue to us. And in any case, we want to reflect the time that's set on the shared server, which may itself be a few seconds adrift from time to time, and not the central atomic clock. So I've put a very short PHP script onto the backup server which does no more than server the current time:
<?php
print(time());
?>
And called that up each day, in a regular (crontab) job on the live system ... the line in my crontab looks something like this:
21 1 * * * /bin/date `/usr/bin/php -r 'echo date("mdHiY.s",file_get_contents("http://backupservername.net/checktime.php"));'`
As technical notes
a) The Crontab job has to run a root to have the authority to set the clock
b) I have (of course) changed the server and file name in my example - simply to avoid encouraging the world to set their time easily from our hosted service by virtue of my publishing this
c) The crontab job should actually run a slightly more complex PHP script that deals with cases of major slippage between the machines, and skip over the synchronization if the remote machine does not respond
We cover crontab on our Introduction to Linux Administration course. Crontab is often used on web servers for regular maintainance tasks, and for periodic logging. We also use it to change the look and feel of the website to different templates for Christmas.