在C语言中,有几种方法可以实现定时程序:
使用`signal`和`alarm`函数
```c
include include include void timer_handler(int signum) { printf("Timer expired!\n"); } int main() { signal(SIGALRM, timer_handler); // 设置定时器,间隔为1秒 alarm(1); // 主程序继续执行 while (1) { printf("Main program is running...\n"); sleep(1); } return 0; } ``` ```c include include include void timer_handler(int signum) { printf("Timer expired!\n"); } int main() { struct sigaction sa; struct itimerval timer; // 为定时器信号设置处理函数 sa.sa_handler = timer_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGALRM, &sa, NULL); // 设置定时器时间间隔 timer.it_value.tv_sec = 1; // 初始超时时间为1秒 timer.it_value.tv_usec = 0; timer.it_interval.tv_sec = 1; // 定时器周期为1秒 timer.it_interval.tv_usec = 0; // 启动定时器 setitimer(ITIMER_REAL, &timer, NULL); while (1) { sleep(1); } return 0; } ``` ```c include include void timer(long time) { clock_t start; long count = 1; start = clock(); while (1) { if ((clock() - start) != (time * CLOCKS_PER_SEC)) { // 时间没有到,啥也不做,空循环 } else { // 时间到了退出循环 printf("%ld ", count++); start = clock(); break; } } } int main() { timer(1); // 设置定时器为1秒 return 0; } ``` ```c include include "tm.h" // 假设这是第三方库的头文件 void timer_callback(void *arg) { printf("定时任务执行啦\n"); } int main() { // 创建定时器 tm_timer_t *timer = tm_timer_create(2000, timer_callback, NULL); // 启动定时器 tm_timer_start(timer); // 等待定时器结束 tm_timer_join(timer); return 0; } ``` ```c include int main() { DWORD dwStart, dwStop; dwStop = GetTickCount(); while (TRUE) { // 上一次的中止值变成新的起始值 dwStart = dwStop; // 此处添加相应控制语句 do { dwStop = GetTickCount(); } while (dwStop - 50 < dwStart); // 50ms的定时器 } return 0; } ``` 这些方法各有优缺点,选择哪种方法取决于你的具体需求,例如定时器的精度、操作系统支持情况以及是否需要处理复杂的定时任务。使用`sigaction`和`setitimer`函数
使用`clock()`函数
使用第三方库
使用`GetTickCount()`函数