Files
pip/pitimer.h
2011-10-09 22:23:52 +04:00

79 lines
1.5 KiB
C++

#ifndef PITIMER_H
#define PITIMER_H
#include <ctime>
#include <csignal>
#include "pithread.h"
#include "pistring.h"
typedef void (*TimerEvent)(void * );
struct PITime {
int seconds;
int minutes;
int hours;
};
struct PIDate {
int day;
int month;
int year; // since 1900
};
class PITimer
#ifdef WINDOWS
: public PIThread
#endif
{
public:
PITimer(TimerEvent slot = 0, void * data = 0);
~PITimer() {stop();}
void setData(void * data_) {data = data_;}
void setSlot(TimerEvent slot_) {ret_func = slot_;}
#ifdef WINDOWS
void reset() {t_st = GetCurrentTime();}
#else
void reset() {clock_gettime(0, &t_st);}
void start(double msecs);
void stop() {if (ti == 0) timer_delete(timer); ti = -1; running = false;}
bool isRunning() const {return running;}
void needLockRun(bool need) {lockRun = need;}
void lock() {mutex_.lock();}
void unlock() {mutex_.unlock();}
#endif
double elapsed_n(); // nanoseconds
double elapsed_u(); // microseconds
double elapsed_m(); // miliseconds
double elapsed_s(); // seconds
private:
#ifdef WINDOWS
void run() {if (ret_func != 0) ret_func(data);}
long int t_st, t_cur;
#else
static void timer_event(sigval e);
bool running;
volatile bool lockRun;
PIMutex mutex_;
int ti;
itimerspec spec;
timespec t_st, t_cur;
timer_t timer;
sigevent se;
#endif
void * data;
TimerEvent ret_func;
};
PITime currentTime();
PIDate currentDate();
PIString time2string(const PITime & time, const PIString & format = "h:mm:ss");
PIString date2string(const PIDate & date, const PIString & format = "d.mm.yyyy");
#endif // PITIMER_H