开发者

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

开发者 https://www.devze.com 2023-01-30 18:48 出处:网络
Well i need to figure 开发者_如何转开发out how to call a function at a certain time if my application is running.

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?


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.)


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.


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


You could install a scheduled task in your system that will notify your application. If your system is Linux you can use cron for example.

0

精彩评论

暂无评论...
验证码 换一张
取 消