Last active
September 19, 2020 08:54
-
-
Save xhimanshuz/9e1bbe49be70054af52d6633614be1a5 to your computer and use it in GitHub Desktop.
Scheduling in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This program is to explain how to schedule tasks in C++ | |
* | |
*/ | |
#include <iostream> | |
#include <string> | |
#include <time.h> | |
#include <iomanip> | |
#include <chrono> | |
#include <thread> | |
#include <unistd.h> | |
/* | |
* To Convert Time string to epoch for scheduling | |
*/ | |
int64_t toEpoch(const std::string timeStr) | |
{ | |
std::time_t time = std::time(nullptr); | |
std::tm t = *std::localtime(&time); // FILL WITH NOW TIME VALUES OR DEFAULT VALUES | |
std::istringstream is(timeStr); | |
is >> std::get_time(&t, "%d/%m/%y %H:%M:%S"); // FILL WITH TIME ACCORDING TO STRING FORMAT | |
std::time_t epoch = std::mktime(&t); | |
return epoch; | |
} | |
/* | |
* wait until now epoch is less than or euqal to startEpoch | |
* When start epoch is less than or queal to now epoch | |
* It will break this loop. | |
*/ | |
void scheduleTask(const std::string &startTime, const std::string &endTime, bool &stop) | |
{ | |
auto startEpoch = toEpoch(startTime); | |
auto endEpoch = toEpoch(endTime); | |
while(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count() <= startEpoch) | |
{ | |
sleep(1); | |
} | |
std::cout<< "Program Started, Do Something!"; | |
// Doing something...! | |
stop = true; | |
} | |
int main() | |
{ | |
bool stop = false; | |
// Start a schedule porgram in new thread without blocking it. | |
std::thread(scheduleTask,"19/09/2020 14:01:50", "19/09/2020 14:00:00", stop).detach(); | |
// Wait for other thread to finished. | |
while(!stop) | |
{ | |
sleep(1); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment