...making Linux just a little more fun!

<-- prev | next -->

Setting the Clock on Linux

By William Park

Background

There are 3 protocols dealing with time: NTP (port 123), Time (port 37), and Daytime (port 13). If you're connecting to the Internet periodically, then synchronizing your clock when you dial up or from crontab is good enough. This applies also to most Linux machines at home or at work, even if they are connected all the time. Here is a short tutorial on how to set your clock using these 3 protocols.

First, you need reference servers to obtain the time from. In Canada,

and in the US, where the number after NTP indicates stratum level of server. Primary NTP (stratum 1) servers are reserved for secondary (stratum 2) NTP servers and should not be used by end users. Of course, you should try to use servers close to you.

The time you see displayed is the CMOS clock time corrected by the drift in /etc/adjtime, so

    hwclock --adjust
    hwclock --hctosys
should be done at boot. Once running, the system clock can be set by any one of the four following methods:
  1. NTP (port 123)
        ntpdate time.nrc.ca time.apple.com time.windows.com
    
  2. Time (port 37)
        netdate time.nrc.ca time.nist.gov time-nw.nist.gov
    
  3. Daytime (port 13)
        set -- `nc time.nist.gov 13`
        date -u --set="$2 $3"
    
  4. Wall Clock
        date --set="16:24:30"
    
On shutdown, set the CMOS clock with
    hwclock --systohc
which will update /etc/adjtime.

rc.clock

You can wrap it up as /etc/rc.d/rc.clock, with something like

    #! /bin/sh

    [ -x /sbin/hwclock ] || exit 1

    case $1 in 
	start)
	    echo "Setting system time from hardware clock."
	    /sbin/hwclock --adjust
	    /sbin/hwclock --hctosys
	    ;;
	stop)
	    echo "Saving system time to hardware clock."
	    /sbin/hwclock --systohc
	    ;;
	sync)
	    /usr/sbin/ntpdate time.nrc.ca time.apple.com time.windows.com
	    ;;
	*)
	    echo "Usage: $0 {start|stop|sync}"
	    ;;
    esac
Then, you can call

 


[BIO] I learned Unix using the original Bourne shell. And, after my journey through language wilderness, I have come full-circle back to shell. Recently, I've been patching features into Bash, giving other scripting languages a run for their money. Slackware has been my primary distribution since the beginning, because I can type. In my toolbox, I have Vim, Bash, Mutt, Tin, TeX/LaTeX, Python, Awk, Sed. Even my shell command line is in Vi-mode.

Copyright © 2004, William Park. Released under the Open Publication license unless otherwise noted in the body of the article. Linux Gazette is not produced, sponsored, or endorsed by its prior host, SSC, Inc.

Published in Issue 108 of Linux Gazette, November 2004

<-- prev | next -->
Tux