example_periodic.c (876B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/time.h> 4 5 #include "src/scheduler.h" 6 7 typedef struct { 8 int64_t start; 9 int64_t interval_ms; 10 int64_t created_at; 11 } TimerCtx; 12 13 static int ticker(int64_t ts, pt_task_t *task) { 14 TimerCtx *ctx = task->udata; 15 16 if (ts - ctx->start >= ctx->interval_ms) { 17 printf("[%lld ms] tick!\n", (long long)(ts - ctx->created_at)); 18 ctx->start = ts; 19 20 if (ts - ctx->created_at >= 5000) { 21 printf("5 seconds elapsed, stopping.\n"); 22 free(ctx); 23 return SCHED_DONE; 24 } 25 } 26 27 return SCHED_RUNNING; 28 } 29 30 int main(void) { 31 TimerCtx *ctx = calloc(1, sizeof(TimerCtx)); 32 33 struct timeval now; 34 gettimeofday(&now, NULL); 35 ctx->created_at = (int64_t)now.tv_sec * 1000 + now.tv_usec / 1000; 36 ctx->start = ctx->created_at; 37 ctx->interval_ms = 1000; 38 39 sched_create(ticker, ctx); 40 sched_main(); 41 return 0; 42 }