How do you call a function once a day at a specific time in C ++?

Well, I need to figure out how to call a function at a specific time if my application is running.

it will probably be in the while loop and checks the time, but I don’t want it to check the time every minute, but I don’t want it to miss the exact time, say 18:00.

Is there any way to do this?

+4
source share
4 answers

EDIT: I don’t know why I assumed it was Windows. I do not see anywhere that he says so. The API information below is only applicable for Windows, but the principle is the same. Boost.Asio has portable asynchronous timers, if not Windows.

Windows Information:. When the application starts, check the remaining interval for the desired event and run Timer Queue Timer at the right time. The timer will appear after the initial interval, and then again after the periodic interval.

CreateTimerQueueTimer Function

Creates a timer timer. This timer expires at the specified time, then after each specified period. When the timer expires, the callback function is called.

It is much more efficient to make this event manageable than to periodically check the clock.

+4
source

If you want to call a specific function from an already running program, use Boost Date Time and Asio .

#include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/asio.hpp> namespace gregorian = boost::gregorian; namespace posix_time = boost::posix_time; namespace asio = boost::asio; asio::io_service io_service_; asio::deadline_timer timer_ (io_service_); 

Then set the time. This is an example using the desired time string, for example "18:00:00". (Note that Boost defaults to UTC for timestamps!)

 gregorian::date today = gregorian::day_clock::local_day(); posix_time::time_duration usertime = posix_time::duration_from_string(time) posix_time::ptime expirationtime (today, usertime); 

Now set the timer to foo() :

 timer_.expires_at (expirationtime); timer_.async_wait (foo); // use Boost::bind() if you want a member function 

You can add as many timers as you want timer_ using the above two code snippets. When everything is ready:

 io_service_.run (); 

Note that this will take the current thread. Therefore, you must call run() from another thread if you want the rest of your program to keep going. (Obviously, use the Boost Thread library for this.)

+8
source

The best way would be to use the operating system tools that provide this, and you only care about writing your function. But if this is not an option, you will just need to check the clock, as you said.

+1
source

You can set a scheduled task on your system that will notify your application. If your system is Linux, you can use cron, for example.

0
source

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


All Articles