Perform a function at a specific time

I would like the user to enter time, for example. 1400h - this will cause the function to work at 1400h.

How can i do this?

Context: I have a client-server program running on one computer - and I need several nodes to send messages at the same time (this is a function, as mentioned above)

edit: I don’t want to use the sleep() function, ideally, since the problem is that the clients will start at different times, and this is much neater as a solution to calling what forces the function to execute at 1400h.

+1
source share
3 answers

You can use std::this_thread::sleep_until , for example

 void main() { auto fire_time = /**/; std::thread thread([&] { std::this_thread::sleep_until(fire_time); fire(); }); thread.join(); } 

You can reorganize this into a helper function, which you are probably looking for:

 template<class Func, class Clock, class Duration> void run_at(Func&& func, const std::chrono::time_point<Clock,Duration>& sleep_time) { std::thread(std::bind([&](const Func& func) { std::this_thread::sleep_until(sleep_time); func(); }, std::move(func))) .detach(); } 
+3
source

If the program runs all the time, use a function, such as sleep , to wait for the time between 14:00 and 14:00. You may need to do this in a separate thread so that the program can perform other functions, or replace sleep with the event loop timeout (if the program is based on event loops).

If the program should exit, you need to use a system object, such as at on Unix, to arrange for the program to restart and execute the code at the specified time.

+1
source

I believe that you need some kind of task manager. This is the basic model. Breeding sleeping threads is a very wrong way to do this job. One manager will know when to run the next task. The challenge is another question. You can create a new thread for each task if you want them to be interactive. Or you can serialize them and run from the manager thread.

0
source

Source: https://habr.com/ru/post/1490664/


All Articles