TimerClock.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "TimerClock.h"
  2. struct _TimerClock {
  3. GObject parent;
  4. TimerClockAction action;
  5. int interval;
  6. gpointer data;
  7. GThread *thread;
  8. gboolean running;
  9. gint64 lastTick;
  10. gint64 currentTime;
  11. };
  12. G_DEFINE_TYPE(TimerClock, timer_clock, G_TYPE_OBJECT);
  13. static void timer_clock_thread_callback(TimerClock *self) {
  14. self->lastTick = g_get_monotonic_time() / 1000;
  15. while (self->running) {
  16. guint now = g_get_monotonic_time() / 1000;
  17. self->currentTime = now - self->lastTick;
  18. if (self->currentTime >= self->interval) {
  19. self->action(self->data);
  20. self->lastTick = now;
  21. self->currentTime = 0;
  22. }
  23. g_usleep(500);
  24. }
  25. }
  26. TimerClock *timer_clock_new(int interval, TimerClockAction action, gpointer data) {
  27. TimerClock *o = TIMER_CLOCK(g_object_new(TIMER_TYPE_CLOCK, NULL));
  28. o->action = action;
  29. o->interval = interval;
  30. o->data = data;
  31. return o;
  32. }
  33. void timer_clock_start(TimerClock *self) {
  34. self->running = TRUE;
  35. self->thread = g_thread_new("timer", (GThreadFunc) timer_clock_thread_callback, self);
  36. }
  37. void timer_clock_stop(TimerClock *self) {
  38. self->running = FALSE;
  39. g_thread_join(self->thread);
  40. self->thread = NULL;
  41. }
  42. gboolean timer_clock_is_running(TimerClock *self) {
  43. return self->running;
  44. }
  45. static void timer_clock_finalize(GObject *self) {
  46. TIMER_CLOCK(self)->running = FALSE;
  47. if (TIMER_CLOCK(self)->thread != NULL) {
  48. g_thread_unref(TIMER_CLOCK(self)->thread);
  49. }
  50. G_OBJECT_CLASS(timer_clock_parent_class)->finalize(self);
  51. }
  52. static void timer_clock_class_init(TimerClockClass *class) {
  53. G_OBJECT_CLASS(class)->finalize = timer_clock_finalize;
  54. }
  55. static void timer_clock_init(TimerClock *self) {
  56. }