Can I run a script if the RTC is updated from NTP?

  • I would like to update an Arduino I have connected via I2C with the correct date and time once I'm sure the Pi has it. Since the Pi is getting the time via NTP, it seems the most obvious would be to have a script run when NTP is successful.

    Is there a mechanism for this? I'm thinking systemd might be involved but not sure what target?

  • The reason I want to grab the NTP is because I don't want to update the Arduino if the Date/Time is not valid (ie wrong because there was no Internet).

    I've created this systemd entry and it seems to work, although I don't know if it still fires if the NTP gets updated after boot.

    [Unit]

    Description=Media Centre Control Panel NTP Updater

    After=time-sync.target

    [Service]

    ExecStart=/storage/MediaCentre/NTPUpdate.sh

    Type=Simple

    [Install]

    WantedBy=multi-user.target

  • The service file looks fine, you should change the Type to "oneshot" though (simple is for programs continuously running in the background, eg if you want to do regular updates in a loop in your script).

    For scripts that should be only run once after startup you should also set "RemainAfterExit=yes" in addition to "Type=oneshot".

    so long,

    Hias

  • The service seems to work, but systems is now adding a service that waits for time sync, which of there's no internet causes boot to hang indefinitely.

    Time to rethink this.

  • The hang is caused by multi-user.target getting an After= dependency on your service, in addition to the Wants=.

    You can avoid that by setting DefaultDependencies=no and manually specifying Before, After and Conflicts. eg:

    Code
    DefaultDependencies=no
    After=time-sync.target
    Before=shutdown.target
    Conflicts=shutdown.target

    Then multi-user.target will only get the Wants= which pulls in your service but not the After= which delays multi-user.target.

    so long,

    Hias