@@ -9,26 +9,55 @@ test ! -c /dev/rtc0 || exit 0
9
9
# This script is intended for services running with systemd.
10
10
command -v systemctl > /dev/null 2>&1 || exit 0
11
11
12
+ echo_with_time_usec () {
13
+ time_usec=$( timedatectl show --property=TimeUSec)
14
+ echo " ${time_usec} , ${1} "
15
+ }
16
+
12
17
# Enable `systemd-time-wait-sync.service` to wait for NTP synchronization at an earlier stage.
13
18
systemctl enable systemd-time-wait-sync.service
14
19
15
20
# For the first boot, where the above setting is not yet active, wait for NTP synchronization here.
16
21
max_retry=60 retry=0
17
22
until ntp_synchronized=$( timedatectl show --property=NTPSynchronized --value) && [ " ${ntp_synchronized} " = " yes" ] ||
18
23
[ " ${retry} " -gt " ${max_retry} " ]; do
19
- time_usec=$( timedatectl show --property=TimeUSec)
20
- echo " ${time_usec} , Waiting for NTP synchronization..."
24
+ if [ " ${retry} " -eq 0 ]; then
25
+ # If /dev/rtc is not available, the system time set during the Linux kernel build is used.
26
+ # The larger the difference between this system time and the NTP server time, the longer the NTP synchronization will take.
27
+ # By setting the system time to the modification time of this script, which is likely to be closer to the actual time,
28
+ # the NTP synchronization time can be shortened.
29
+ echo_with_time_usec " Setting the system time to the modification time of ${0} ."
30
+
31
+ # To set the time to a specified time, it is necessary to stop systemd-timesyncd.
32
+ systemctl stop systemd-timesyncd
33
+
34
+ # Since `timedatectl set-time` fails if systemd-timesyncd is not stopped,
35
+ # ensure that it is completely stopped before proceeding.
36
+ until pid_of_timesyncd=$( systemctl show systemd-timesyncd --property=MainPID --value) && [ " ${pid_of_timesyncd} " -eq 0 ]; do
37
+ echo_with_time_usec " Waiting for systemd-timesyncd to stop..."
38
+ sleep 1
39
+ done
40
+
41
+ # Set the system time to the modification time of this script.
42
+ modification_time=$( stat -c %y " ${0} " )
43
+ echo_with_time_usec " Setting the system time to ${modification_time} ."
44
+ timedatectl set-time " ${modification_time} "
45
+
46
+ # Restart systemd-timesyncd
47
+ systemctl start systemd-timesyncd
48
+ else
49
+ echo_with_time_usec " Waiting for NTP synchronization..."
50
+ fi
21
51
retry=$(( retry + 1 ))
22
52
sleep 1
23
53
done
24
54
# Print the result of NTP synchronization
25
55
ntp_message=$( timedatectl show-timesync --property=NTPMessage)
26
- time_usec=$( timedatectl show --property=TimeUSec)
27
56
if [ " ${ntp_synchronized} " = " yes" ]; then
28
- echo " ${time_usec} , NTP synchronization complete."
57
+ echo_with_time_usec " NTP synchronization complete."
29
58
echo " ${ntp_message} "
30
59
else
31
- echo " ${time_usec} , NTP synchronization timed out."
60
+ echo_with_time_usec " NTP synchronization timed out."
32
61
echo " ${ntp_message} "
33
62
exit 1
34
63
fi
0 commit comments