Выполнить скрипт после синхронизации ntpd

У меня малиновый пи с raspbian. Я хотел бы выполнить скрипт сразу после синхронизации времени с ntpd, моему скрипту нужна правильная дата и время. Как я могу это сделать?


person davidovv    schedule 22.01.2015    source источник


Ответы (2)


Предполагая, что у вас есть пользователь, у которого есть права на вызов ntpdate (другими словами, кто может настроить системное время), вы можете использовать следующий скрипт, который я использую в приведенном ниже примере для ntp-сервера 0.ca.pool.ntp. организация

#!/bin/bash

NEEDS_SYNC=1
while [ "$NEEDS_SYNC" -ne "0" ]; do
    ntpdate -t 4     0.ca.pool.ntp.org
    NEEDS_SYNC=$?    # If this variable is set ot 0, time sync worked
    sleep 2
done

# RUN THE SCRIPT THT NEEDS ntp SYNC'D TIME HERE

Обратите внимание, что вам может потребоваться установить пакет 'ntpdate', чтобы это работало.

person Jorge Torres    schedule 22.01.2015
comment
я не понимаю $? часть что такое $? - person davidovv; 22.01.2015
comment
извините, трудно было найти $? в гугле, но я наконец понял, $? статус выхода команды - person davidovv; 22.01.2015
comment
Я только что увидел ваш вопрос, извините. Я рад слышать, что вы поняли это. Правильно, $? содержит статус выхода ntpdate, который возвращает ноль только в том случае, если дата установлена ​​эффективно. - person Jorge Torres; 22.01.2015

Правильный способ сделать это — использовать ntp-wait. ntp-wait был создан специально для таких ситуаций. Вот справочная страница:

ntp-wait(1)                     User Commands                    ntp-wait(1)

NAME
       ntp-wait - Wait for ntpd to stabilize the system clock

SYNOPSIS
       ntp-wait [-flag [value]]... [--opt-name [[=| ]value]]...

       All arguments must be options.

DESCRIPTION
       will  send  at  most  num-tries queries to sleeping for secs-between-
       tries after each status return that says has not yet produced a  syn‐
       chronized and stable system clock.

       will do this quietly, unless the v flag is provided.

OPTIONS
       -n num-tries, --=num-tries
              Number  of  times to check ntpd.  This option takes an integer
              number as its argument.  The default num-tries for this option
              is:
                   100

              The  maximum  number  of times we will check ntpd to see if it
              has been able to synchronize and stabilize the system clock.

       -s secs-between-tries, --=secs-between-tries
              How long to sleep between tries.  This option takes an integer
              number  as  its  argument.  The default secs-between-tries for
              this option is:
                   6

              We will sleep for @file{secs-between-tries} after  each  query
              of ntpd that returns "the time is not yet stable".

       -v, -- Be verbose.

              By  default,  ntp-wait  is silent.  With this option, ntp-wait
              will provide status information.

       -?, --help
              Display usage information and exit.

       -!, --more-help
              Pass the extended usage information through a pager.

       - [{v|c|n}], --version[={v|c|n}]
              Output version of program and exit.  The default mode is  `v',
              a  simple version.  The `c' mode will print copyright informa‐
              tion and `n' will print the full copyright notice.


EXIT STATUS
       One of the following exit values will be returned:

       0      Successful program execution.

       1      The operation failed or the command syntax was not valid.
person dfc    schedule 22.01.2015
comment
Я бы хотел, чтобы ntp-wait был лучше, если бы у него была такая опция, как -n 0 (ждать вечно). Для текущей опции мне нужно написать очень большое число (например, оценить оставшуюся жизнь :), и кто-то еще, кто читает код, будет смущен большим считать и считать секунды*пытается понять, что смысла нет... Я бы пожаловался портному, что костюм не подходит :) - person davidovv; 23.01.2015