#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <sys/types.h>
#include <unistd.h>
usingnamespace std;
void verifySystem() {
cout << "HEY!.. We are checking the system.." << endl;
// Here i have to the check if are running 5 programs
sleep(1); // Only to check, because the checking lasted more than 1 second, sure..
}
char buffer [20];
char *times () {
time_t now = time (0);
struct tm *RightNow;
RightNow=localtime ((const time_t*)&now);
strftime (buffer, 20, "%H:%M:%S", RightNow);
return buffer;
}
int main () {
while (strcmp (times (), "18:01:00") <= 0) {
if (strcmp (times (), "08:00:00") == 0) {
verifySystem();
}
if (strcmp (times (), "08:30:00") == 0) {
verifySystem();
}
if (strcmp (times (), "09:00:00") == 0) {
verifySystem();
}
// The same for 09:30:00, 10:00:00, .... 18:00:00
}
return 0;
}
The above code works but I have some problems:
1) In the while loop, if I run the code (say at 7:00:00) until it arrives at 08:00:00 consumes 100% CPU. The same problem is when he call the function and is waiting 30 minutes consuming 100% CPU..
2) There are probably a better way to call the function verifySystem (); every half hour and avoid to repeat the IF twenty times..
Hi mik2718, thanks!!.. I modified the code a bit.. Yes, I know the linux cron but for this case, does not help. I have to do this in C++ even if i use a library in C :) hehe...
you should make enhancements in your code .
first you should call time(NULL) to retrieve the current .
then convert you required time e.g. 08:00:00 to time_t using mktime .
then take the difference between these timings and then push your application into sleep mode for those number of seconds and after that re start your loop.
this will not consume your CPU when your program will be idle.
Well, finally is solved, to control that does not consume 100% CPU, I put to sleep 1 second between each loop cycle. As I need to check the system every half hour, I call the function in MM:SS > 00:00 and 30:00. As on Friday at 21:00 GMT Hs I need to finish and clean, I put the condition day of the week and time GMT:
while (1) {
char *day = dayOfWeek(); // function that give me the day of the week
// difference and allocation to GMT
time_t tGMT = time(NULL);
tm tm2 = *gmtime(&tGMT);
// Every half hour, run the function
if ((strcmp (minuteSecond(), "00:00") == 0) || // 00:00 (MM:SS)
(strcmp (minuteSecond(), "30:00") == 0)) { // 30:00 (MM:SS)
verifySystem();
}
// If is Friday and 21:00:00 GMT, clean and finish
if ((strcmp (day,"friday") == 0) &&
(strcmp (hourMinuteSecond(),"21:00:00") == 0)) {
cout << "Today is friday!!!..." << endl;
finishAndClean(); // Call to the finishAndClean function
break; // Stop and exit
}
sleep(1); // sleep 1 second to avoid consume 100% CPU
strcpy(day, ""); // clear the day of the week
}