0

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.

manav m-n
  • 11,136
  • 23
  • 74
  • 97

2 Answers2

3

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).

unwind
  • 391,730
  • 64
  • 469
  • 606
  • It's for a stand-alone system, say, a space-craft which hibernates for long time period without network connectivity. – manav m-n Nov 25 '14 at 10:09
  • 1
    @Manav: If the system does not have a reliable, permanent system clock (more accuracy than a second in 7 years, far better than standard quartz), just forget it. The computer cannot guess how long it was hibernated. –  Nov 25 '14 at 10:18
-1

How about:

on computer start if file does not exist create it and write using binary time_t integer representing now.

while cpu is on, every second check whether now - stored time >= 7 years and if so do whatever you want - eg buzzing sound.

you will need to keep running this every second, but could get you started.

#include <time.h>
#include <stdio.h>

// 7*52*7*24*60*60
#define TIMEDIFF 220147200

int main(int argc, char* argv[]) {

   FILE* fp = fopen(argv[1], "r");
   if(!fp) {
      fp = fopen(argv[1], "w");
      time_t starttime = time(NULL);
      fwrite(&starttime, sizeof(time_t), 1, fp);
      printf("time_t value when set now: %u\n", starttime);
   }
   else {
       time_t timethen;
       size_t bytes = fread(&timethen, sizeof(time_t), 1, fp);
       printf("time_t value when set: %u\n", timethen);

       time_t testnow = time(NULL);
       if(difftime(timethen, testnow) > TIMEDIFF)
          printf("Your 7 years is up!");
   }

   fclose(fp);
   return 0;
}
Angus Comber
  • 9,316
  • 14
  • 59
  • 107