No Battery Backed Real Time Clock Linux Scripts

Sometimes on embedded Linux systems the system will always want time to move
forward but the cost of adding a battery backed real time clock is unacceptable.
In this kind of situation, I’ve found the following solution to be useful.

At shutdown we will write out a file to the “disk” (usually flash memory) with a
timestamp of the current time. At boot, after systemd moves the clock ahead to
its compile time but prior to starting any processes which need time to be
roughly right and before any time sync beings (ntp, systemd-timesyncd, etc), we
will restore the saved timestamp to be the system’s current time. We make sure
to store the timestamp in a format which will always have later times be larger
numbers so we can easily compare them and we don’t use the normal seconds since
the Unix epoch as there might be interesting issues in about 20 years. This
makes the restore process slightly more complicated as it’s not a normal format
to store a Unix timestamp in but it’s much easier for humans to understand when
they look at the timestamp file.

My examples use systemd but you can do something similar with other init
systems, too. Just be sure to restore the time as early as you can in the boot
sequence and to save the time prior to unmounting your read/write flash memory
during shutdown.

There’s two components to this scheme, first is the systemd service file which
will run the script at startup and shutdown (replace with your own mechanism for
non-systemd init). Key here is that the ExecStart script run may exit with a
non-zero result, such as if the current time is already ahead of the saved
timestamp so we need to allow for this to fail: