Monday, June 14, 2010

Sync time with external server in Debian

You can synchronize your local computer time with external time servers. You need install ntpdate:
apt-get -y install ntpdate
Try update your time manually:
deby:~# ntpdate pool.ntp.org
12 Jun 00:04:16 ntpdate[1903]: step time server 62.80.187.114 offset -291.468062 sec
Here is a script that syncs the time with external server, adjusts clock drift and finally sets the hardware clock to current system time (file /usr/local/sbin/sync-time).
#!/bin/bash

server=pool.ntp.org

# Sleep a random amount, not greater than 2 minutes
sleep_time=$(($RANDOM % 120))

echo "Sleeping for $sleep_time seconds..."
/bin/sleep $sleep_time

# Sync the time with external server
echo "Sync time with $server."
/usr/sbin/ntpdate -s $server || exit 1

# Adjusts clock drift
/sbin/hwclock --adjust

# Set the hardware clock to current system time
/sbin/hwclock --systohc

Here we are going to schedule a cron job on system startup (file /usr/local/sbin/sync-time, symbolic link from /etc/cron.d/sync-time):
#
# Regular cron job for time synchronization
#
PATH=/usr/local/sbin
HOME=/
LOG=/dev/null

# Every 23 hours, e.g. 2:11, 13:11, etc
11 */23 * * * root test -x /usr/local/sbin/sync-time && sync-time > $LOG
The next time your system restarts it will automatically synchronizes clock with external server. Please note that the system sync the time each time the network interface is up (see ntpdate script in /etc/network/if-up.d/).

1 comment :

  1. Nice and precise!
    Thanks for posting this. Made a quick search on the internet nice and quick.

    ReplyDelete