major4x
major4x

Reputation: 442

How to Awake at Certain Time in C++/Boost

I couldn't figure out which Boost C++ library to use to schedule a bunch of alarms at certain times of the day. I am sure it is something very common and simple. Any pointers would be welcome. I thought of creating a thread for each alarm and sleeping it but there should be something more elegant.

Upvotes: 0

Views: 990

Answers (2)

Marty
Marty

Reputation: 116

You could use boost timers and always set the timer to run at the closest date of an alarm having to be triggered. http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/tutorial/tuttimer2.html

An example can also be found here C++ Boost ASIO simple periodic timer? In the stackOverflow example, the interval would be the minimum between all NextAlarmRun - currentTime.

In short

1) save all next alarm times

2) create timer and set to closest alarm time (A1)

3) timer is triggered, does stuff

4) change A1 to new value

5) calculate closest alarm time

6) reset timer to closest alarm time

Edit: In order to avoid calculating the closest alarm time every time, you can use an orderd list or vector and once an alarm is run, remove it and insert the new alarm time in the proper place in your structure. I wouldn't advise using a queue, since it might be possible that the current alarm to have to be scheduled before the last one in your queue.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490408

I'd probably create a priority_queue of alarm times (note: you'll have to use > as the comparison operator for the earliest time to be treated as highest priority), then have a single thread sleep until the first time. When it wakes, have it execute what's needed, then sleep until the alarm time for the next item in the priority queue.

Upvotes: 2

Related Questions