以下程序为闹钟,部分使用了boost库,但可修改
/**
* @brief : alarm clock and alarm timer
* @author : comwise
* @note : timer, you must set correct begin time
* @version : V1.0 2016/06/03
*/
#ifndef _ALARM_TIMER_H_
#define _ALARM_TIMER_H_
#include <string>
#include <ctime>
#include <cmath>
#include <boost/limits.hpp>
#include <boost/date_time.hpp>
class alarm_clock
{
public:
alarm_clock(void) {
restart();
}
void restart() {
start_time_ = std::clock();
}
double elapsed() {
return double(std::clock() - start_time_) / CLOCKS_PER_SEC;
}
double elapsed_max() const {
return (double((std::numeric_limits<std::clock_t>::max)())
- double(start_time_)) / double(CLOCKS_PER_SEC);
}
double elapsed_min() const {
return double(1) / double(CLOCKS_PER_SEC);
}
~alarm_clock(void);
private:
std::clock_t start_time_;
};
enum alarm_week
{
week_sun = 0x1, // 2^0
week_mon = 0x2, // 2^1
week_tue = 0x4, // 2^2
week_wed = 0x8, // 2^3
week_thu = 0x10, // 2^4
week_fri = 0x20, // 2^5
week_sat = 0x40, // 2^6
};
typedef __int64 alarm_duration_t; // use alarm_week |
typedef boost::posix_time::ptime alarm_time_t;
class alarm_timer
{
public:
//_start_time, between date and time must space, date and time accepted delimiters are "-:,./"
// eg.2016-07-01 01:02:03" or "2016/01/01 010203"
// alarm_duration_t; // use alarm_week |
alarm_timer(const std::string& _start_time = "1970/01/01 00:00:00", alarm_duration_t _elapsed = 0) {
reset(_start_time, _elapsed);
}
void reset(const std::string& _start_time, alarm_duration_t _elapsed){
start_time_ = boost::posix_time::time_from_string(_start_time);
elapsed_ = _elapsed;
}
int get_current_week() {
return boost::gregorian::day_clock::local_day().day_of_week();
}
alarm_time_t get_current_time() {
return boost::posix_time::second_clock::local_time();
}
// if date is same, then compare time
// return elapsed time in normalized number of seconds (0..60)
alarm_duration_t get_diff_time() {
if ((int)std::pow((float)2, get_current_week()) & elapsed_) {
return (start_time_.time_of_day().total_seconds() -
get_current_time().time_of_day().total_seconds());
}
else {
return _I64_MIN;
}
}
private:
alarm_time_t start_time_;
alarm_duration_t elapsed_;
};
#endif
测试程序如下
alarm_timer timer;
while (true)
{
SLEEP(100);
timer.reset(job.cycle_begin, job.cycle_value);
alarm_duration_t diff_time = timer.get_diff_time();
if(abs(diff_time) < 1) {
//do it
}
}