I want to write a program to run a countdown timer with initial start value of, say, 7 years. The computer can reboot in between. I can think of file based approach:
open file
if file_empty write initval = 7 years
while cpu_on
write timestamp to file
sleep for 1 sec
However, how can I find the time elapsed between reboots? Accuracy within 1 sec is fine for me. Assume code is for a stand-alone system, say, a space-craft which hibernates for long time period without permanent network connectivity.
It seems way easier to just find out the current system time, and compute the countdown timer's value backwards from that.
For instance, say you you want to count down to 2021-05-09. The value of the timer is then always going to be the difference between that time and the current time. As the current time increases, the timer's will decrease.
This will be accurate as long as the system clock is accurate, which it most likely will be on a modern, network-connected system. It doesn't rely on files to keep state, which seems very brittle and cumbersome. If there is no other way to find out current real-world time, then you cannot handle reboots. Check if the platform has some form of battery-backed timer that survives main CPU reboots, that's pretty common in embedded systems (and old PCs).