3

I'm writing a software in C and it is running as a systemd service. I need the service to run after time has synced or alternatively, I need a way for my C program to identify if time has synced.

I'm not using GPS or RTC. Just the plain Raspberry (both Zero W and 3B+).

I'm using Raspbian Strecth. I was trying to use time-sync.target but it still call my service before date/time is synced.

How can I detect if system has updated its time?

3 Answers 3

2

timedatectl will show if synced

               Local time: Tue 2019-11-19 09:59:09 AEDT
           Universal time: Mon 2019-11-18 22:59:09 UTC
                 RTC time: n/a
                Time zone: Australia/Sydney (AEDT, +1100)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no

/var/lib/systemd/timesync/clock shows last synch time (NOTE this is a zero length file - look at the timestamp)

May be /var/lib/systemd/clock on older Debian OS

NOTE Raspbian Stretch DOES NOT use ntpd

1
  • I was able to manage it with timedatectl. Thank you. Regarding /var/lib/systemd/clock, I don't know what to compare it with, to determine if system has synced or not.
    – Diogo Melo
    Nov 19, 2019 at 23:54
2

If you install ntpd instead of timesyncd, you can check out the first line of the output of ntpstat:

$ ntpstat | head -n1
unsynchronised

... later on ..

$ ntpstat | head -n1
synchronised to NTP server (10.5.26.10) at stratum 2

Inside a script or a C program, use the return code:

ntpstat returns 0 if clock is synchronised. ntpstat returns 1 if clock is not synchronised. ntpstat returns 2 if clock state is indeterminant, for example if ntpd is not contactable.

2

Since systemd 239 there is a systemd-time-wait-sync.service available that you can just use in your systemd service to start After=systemd-time-wait-sync.service. For further information look at How can I delay the startup of systemd services until the datetime is set (no RTC on the Raspberry Pi). Raspbian Buster comes with systemd 241.

The problem is that you use old-stable Raspbian Stretch which comes with systemd 232 so the nice time wait service isn't available in that version. For this situation you can look at the journal for a message about time syncing. I have made a service for this so you can also use it to start After= it. You will find it also at How can I delay the startup of systemd services until the datetime is set (no RTC on the Raspberry Pi).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.