Created
February 26, 2017 07:42
-
-
Save hallazzang/bdb17078e7820f3fac7ac2612cc58819 to your computer and use it in GitHub Desktop.
Implementing periodic events in C (Windows)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <Windows.h> | |
typedef struct { | |
void (*handler)(char *); | |
char parameter[128]; | |
int interval, last_emitted; | |
} Event; | |
Event events[128]; | |
int event_count; | |
void add_event(void (*handler)(char *), char parameter[], int interval) { | |
events[event_count].handler = handler; | |
strcpy(events[event_count].parameter, parameter); | |
events[event_count].interval = interval; | |
events[event_count].last_emitted = 0; | |
++event_count; | |
} | |
void run() { | |
int now = GetTickCount(); | |
for (int i = 0; i < event_count; ++i) { | |
events[i].last_emitted = now; | |
} | |
while (1) { | |
now = GetTickCount(); | |
for (int i = 0; i < event_count; ++i) { | |
if (now - events[i].last_emitted >= events[i].interval) { | |
events[i].handler(events[i].parameter); | |
events[i].last_emitted = now; | |
} | |
} | |
Sleep(10); | |
} | |
} | |
void say(char *message) { | |
printf("Message: %s\n", message); | |
} | |
int main() { | |
add_event(say, "Hello", 1000); | |
add_event(say, "Goodbye", 1500); | |
run(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment