476

I am running Ubuntu on an ARM based embedded system that lacks a battery backed RTC. The wake-up time is somewhere during 1970. Thus, I use the NTP service to update the time to the current time.

I added the following line to /etc/rc.local file:

sudo ntpdate -s time.nist.gov

However, after startup, it still takes a couple of minutes until the time is updated, during which period I cannot work effectively with tar and make.

How can I force a clock update at any given time?


UPDATE 1: The following (thanks to Eric and Stephan) works fine from command line, but fails to update the clock when put in /etc/rc.local:

$ date ; sudo service ntp stop ; sudo ntpdate -s time.nist.gov ; sudo service ntp start ; date
Thu Jan  1 00:00:58 UTC 1970
 * Stopping NTP server ntpd     [ OK ] 
 * Starting NTP server          [ OK ] 
Thu Feb 14 18:52:21 UTC 2013

What am I doing wrong?


UPDATE 2: I tried following the few suggestions that came in response to the 1st update, but nothing seems to actually do the job as required. Here's what I tried:

  1. Replace the server to us.pool.ntp.org
  2. Use explicit paths to the programs
  3. Remove the ntp service altogether and leave just sudo ntpdate ... in rc.local
  4. Remove the sudo from the above command in rc.local

Using the above, the machine still starts at 1970. However, when doing this from command line once logged in (via ssh), the clock gets updated as soon as I invoke ntpdate.

Last thing I did was to remove that from rc.local and place a call to ntpdate in my .bashrc file. This does update the clock as expected, and I get the true current time once the command prompt is available.

However, this means that if the machine is turned on and no user is logged in, then the time never gets updates. I can, of course, reinstall the ntp service so at least the clock is updated within a few minutes from startup, but then we're back at square 1.

So, is there a reason why placing the ntpdate command in rc.local does not perform the required task, while doing so in .bashrc works fine?

ysap
  • 7,191

18 Answers18

621

Instead of ntpdate (which is deprecated), use ntpd:

sudo service ntp stop
sudo ntpd -gq
sudo service ntp start

The -gq tells the ntp daemon to correct the time regardless of the offset (g) and exit immediately (q) after setting the time.

αғsнιη
  • 36,350
369

Probably the ntp service is running, that's why ntpdate can't open the socket (port 123 UDP) and connect to ntp server.

Try from command line:

sudo service ntp stop
sudo ntpdate -s time.nist.gov
sudo service ntp start

If you want to put this in /etc/rc.local use the following:

( /etc/init.d/ntp stop
until ping -nq -c3 8.8.8.8; do
   echo "Waiting for network..."
done
ntpdate -s time.nist.gov
/etc/init.d/ntp start )&
Eric Carvalho
  • 55,453
97

Use timedatectl (systemd service unit) to set the time. ntp is deprecated.

sudo systemctl restart systemd-timesyncd.service

You can check the time was updated reading the logs with journalctl -xe | tail.

Status with timedatectl status and config in /etc/systemd/timesyncd.conf.

Reference

Pablo Bianchi
  • 17,371
xiaoyifang
  • 1,107
73

Use sntp to set the time immediately. Some examples from its man page:

USAGE
     sntp ntpserver.somewhere
             is the simplest use of this program and can be run as an unprivileged command to check the current time and error in the local clock.
 sntp -Ss -M 128 ntpserver.somewhere
         With suitable privilege, run as a command or from a cron(8) job, sntp -Ss -M 128 ntpserver.somewhere will request the time from the server, and if that server reports that it is
         synchronized then if the offset adjustment is less than 128 milliseconds the correction will be slewed, and if the correction is more than 128 milliseconds the correction  will
         be stepped.

 sntp -S ntpserver.somewhere
         With suitable privilege, run as a command or from a cron(8) job, sntp -S ntpserver.somewhere will set (step) the local clock from a synchronized specified server, like the (dep‐
         recated) ntpdate(8), or rdate(8) commands.

It does work with any ntp time server. A convenient list of servers can be found on ntppool.org.

You need sudo privileges, for example:

sudo sntp -Ss -M 128 0.de.pool.ntp.org
yucer
  • 208
Guest
  • 731
43

As others have pointed out the best solution is to instruct ntpd to ignore the panic threshold, which is 1000 seconds by default. You can configure the panic threshold in one of two ways:

  • edit /etc/default/ntp and ensure that the -g option is present.
  • edit /etc/ntp.conf and place tinker panic 0 at the top

So far this is essentially what others have recommended however there is one more step I think you should take. Install the fake-hwclock program:

# apt-get install fake-hwclock


fake-hwclock: Save/restore system clock on machines without working RTC hardware

 Some machines don't have a working realtime clock (RTC) unit, or no
 driver for the hardware that does exist. fake-hwclock is a simple set
 of scripts to save the kernel's current clock periodically (including
 at shutdown) and restore it at boot so that the system clock keeps at
 least close to realtime. This will stop some of the problems that may
 be caused by a system believing it has travelled in time back to
 1970, such as needing to perform filesystem checks at every boot.

 On top of this, use of NTP is still recommended to deal with the fake
 clock "drifting" while the hardware is halted or rebooting.

With fake-hwclock installed your machine will not start up thinking it is 1970 all over again. When your machine boots up it will set its clock to the timestamp fake-hwclock wrote during the last reboot/shutdown. This means you can have a somewhat correct clock in case there are network issues when you boot up.

dfc
  • 1,587
13

ntpdate is a program different from the net dameon. NTPDate is probably erroring out on boot because ntpd is running on that socket.

From the command line, run

# sudo service ntp stop ; sudo ntpdate -s time.nist.gov ; sudo service ntp start

You could also uninstall ntpd all together (apt-get remove ntp) and add a cron script to use ntpdate every hour or so.

UPDATE

ntp service probably won't have meaningful value for you on this system, so remove that first.

# sudo apt-get remove ntp

Now add the command:

ntpdate -sb time.nist.gov

to /etc/rclocal

Reboot. Should be good at that point.

Stephan
  • 590
11
rdate -s tick.greyware.com

if all you want to do is set the clock once, simple

batflaps
  • 211
10

Check out this one (no apt, no service):

sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"

Cheers to Prashant, who solved that issue

Joachim
  • 103
9

Note that some current Ubuntu based systems don't even use the NTP service by default now. On my Linux Mint 19 (Ubuntu 18.04) machine, time is kept by systemd-timesyncd.

So to get an up to date time after it has lost sync, I just run

sudo systemctl restart systemd-timesyncd

Since 15.04 Ubuntu uses systemd by default. Therefore critical systems like time are managed through systemd. To find what service your system is using run something like

systemctl list-unit-files | grep -E 'ntp|timesyncd'

For TechJS on 16.04 the service was ntp. For myself on Ubuntu 18.04 (Mint 19) the service is systemd-timesyncd. Interestingly, I logged into a 16.04 server I have and it uses systemd-timesyncd as well.

8

The correct way to do this on a Debian / Mint / Ubuntu (or other Debian derivative) system is to have the line

NTPD_OPTS="-g"

in the file

/etc/default/ntp

This ensures that when ntpd is started from the /etc/init.d/ntp script, it runs with the "-g" option, viz

 start-stop-daemon --start --quiet --oknodo --pidfile /var/run/ntpd.pid --startas /usr/sbin/ntpd -- -p /var/run/ntpd.pid -g -u 124:128

to allow ntpd to correct the system time when it is more than 1000 s out, eg when the system time is January 1st 1970 on startup because there is no hardware RTC.

7

tlsdate sets the local clock by securely connecting with TLS to remote servers and extracting the remote time out of the secure handshake. Unlike ntpdate, tlsdate uses TCP, for instance connecting to a remote HTTPS or TLS enabled service, and provides some protection against adversaries that try to feed you malicious time information.

$ tlsdate -V -n -H encrypted.google.com
slm
  • 3,155
Kokizzu
  • 518
4

Try using the -b option to step the time.

Cry Havok
  • 1,342
2

Well,

I am running a raspbian (debian wheezy) on my raspberry pi, which doesn't have the hwclock. I found it handy to write a little script and run it after my internet interface is up, so that I am sure that the moment the network becomes available, the clock gets updated.

First check that you have the ntpdate package by running

sudo apt-get update
sudo apt-get install ntpdate

You need to add the following into your /etc/network/interfaces (surely eth0 here is just an example):

auto eth0
    iface eth0 inet dhcp
    post-up /usr/local/sbin/update-time.sh

And create the following script in /usr/local/sbin/update-time.sh (don't forget to make it executable by chmod):

#!/bin/bash
# This script checks if the ntp process is running, stops it, updates the system time, starts it again

ps cax | grep -c ntpd > /dev/null
onoff=$?
if [ "$onoff" -gt 0 ]; then
    echo "stopping ntpd..."
    service ntp stop
    echo "ntpd stopped"
else
    echo "ntpd not running, ready to update the date"
fi


isinstalled=$(dpkg-query -l | grep -c ntpdate)
if [ "$isinstalled" -gt 0 ]; then
    ntpdate -t 3 -s ntp4.stratum2.ru
    echo "date and time update executed"
else
    echo "ntpdate package not installed, can't update using ntp"
fi

echo "restarting ntpd..."
service ntp start 
echo "ntpd running"
echo "printing current date and time:"
date

exit
1

If you are on systemd you could use this command:

sudo systemctl restart ntp
# or
sudo systemctl restart ntp.service

And then the time gets updated within near 10-15 seconds.
Tested on ubuntu mate 16.04

1

The ntpd algorithms discard sample offsets exceeding 128 ms, unless the interval during which no [absolute value of] sample offset is less than 128 ms exceeds 900s. The first sample after that, no matter what the offset, steps the clock to the indicated time. In practice this reduces the false alarm rate where the clock is stepped in error to a vanishingly low incidence.

Normally, ntpd exits if the offset exceeds the sanity limit, which is 1000 s by default. This can be turned off with the -g option:

-g Normally, ntpd exits if the offset exceeds the sanity limit, which is 1000 s by default. If the sanity limit is set to zero, no sanity checking is performed and any offset is acceptable. This option overrides the limit and allows the time to be set to any value without restriction; however, this can happen only once. After that, ntpd will exit if the limit is exceeded. This option can be used with the -q option.

both from http://doc.ntp.org/4.1.0/ntpd.htm

-Jonathan Natale

Elder Geek
  • 36,752
1

ntpd and ntpdate run by default using a restricted port (UDP 123). If you are behind a firewall, ntpd will never work, but ntpdate can work with the -u option. For example: ntpdate -u 0.ubuntu.pool.ntp.org or ntpdate -u time.nist.gov should both work fine.

Ron
  • 20,938
1

If you can afford the time to wait whatever time it takes before your system gets in sync, you can use the ntp-wait command:

ntp-wait || exit -1 
# i believe this would exit the script if it fails, but not sure of ntp-wait return codes, learn this first.

echo Time is synced, go ahead with backup
tar
rsync etc.
muru
  • 207,228
0

Besides recommending to stop the local time server (ntpd or timesyncd), then ntpdate -bs server or ntpd -gq, and after that starting again the time server to keep the time synchronized as many suggested (these steps could be in an @reboot cron job script; see man 5 crontab for details), could be necessary to adjust the Time Zone for the time commands to report the desired time/date.

For Ubuntu and the like use: dpkg-reconfigure tzdata and select the right locale. It keeps its value between restarts.

Fjor
  • 314
  • 2
  • 10