/*******************************************************
 *** RunTime.cmm - Execute commands at supplied time ***
 *******************************************************/

#include <Message.lib>

// define TIME_CHECK_DELAY for how long to delay in between each time
// checking if the RunTime has come yet.  This time is in milliseconds so
// 1000 is 1 second. This time is not exact so setting to 60000 (60 seconds)
// might miss an entire minute. Less then 100 would probably take up more
// processor time than you want, but still not very much
   #define  TIME_CHECK_DELAY  5000  // check every 5 seconds


// Get time of day to run command
   do {
      GetCurrentTime(hour,minute,second);
      printf("\nTime is %02d:%02d",hour,minute);
      printf("\nEnter time to run command (0:00 -> 23:59) ");
      TimeString = gets();
   } while ( 2 != sscanf(TimeString,"%d:%d",RunHour,RunMinute)
          || RunHour < 0  ||  23 < RunHour
          || RunMinute < 0  ||  59 < RunMinute );

// Get Command to run
   printf("\nCommand to run: ");
   RunCommand = gets();

// Show message for what will happen
   ScreenClear();
   printf("Command: %s\n",RunCommand);
   printf("Scheduled time: %02d:%02d:00\n",RunHour,RunMinute);

// Minimize this window so it's not in the way for so long
   PostMessage(ScreenHandle(),WM_SYSCOMMAND,SC_MINIMIZE,0);

// Wait until the specified time
   DisplayedSecond = -1; // force current time to print
   do {
      GetCurrentTime(CurrentHour,CurrentMinute,CurrentSecond);
      if ( CurrentSecond != DisplayedSecond )
         printf("\rCurrent Time:   %02d:%02d:%02d",
                CurrentHour,CurrentMinute,DisplayedSecond=CurrentSecond);
      suspend(TIME_CHECK_DELAY);
   } while ( CurrentHour != RunHour  ||  CurrentMinute != RunMinute );
   printf("\n");

// Execute the command
   spawn(P_NOWAIT,RunCommand);

GetCurrentTime(hour,minute,second)
{
   now = localtime(time());
   hour = now.tm_hour;
   minute = now.tm_min;
   second = now.tm_sec;
}

