Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a function once a day at a certain time in c++?

Tags:

c++

timer

Well i need to figure out how to call a function at a certain time if my application is running.

it will probably be in a while loop and check 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 do to this?

like image 873
Tom Avatar asked Dec 08 '22 00:12

Tom


2 Answers

If you want to call a specific function from within a program that's already running, use Boost's Date Time library 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 a string of the desired time, like "18:00:00". (Note that Boost defaults to UTC for the 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 call 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 to timer_ by using the above two code snippets. When everything is ready:

io_service_.run ();

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

like image 151
chrisaycock Avatar answered Jan 22 '23 15:01

chrisaycock


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

Windows Info : When your app starts up, check the interval remaining to your desired event and start a Timer Queue Timer to pop at the appropriate time. The timer will pop after an initial interval, and then repeatedly after a periodic interval.

CreateTimerQueueTimer Function

Creates a timer-queue timer. This timer expires at the specified due time, then after every specified period. When the timer expires, the callback function is called.

Much more efficient to make this event-driven than to periodically check the clock.

like image 43
Steve Townsend Avatar answered Jan 22 '23 16:01

Steve Townsend