如何定期自动调用函数? [英] how to call a function automatically at regular intervals?
问题描述
我正在编写一个C程序来连接以固定间隔提供数据的串行设备,我需要以固定间隔在串行端口上查找输入.这可以通过读取"功能来完成.但是我不知道如何以固定的时间间隔频繁调用它?
Hi I am writing a C program to interface a serial device which gives data at regular intervals, i need to look for the inputs at the serial port at regular intervals. this can be done by a ' read' function . but i dont know how to call it frequently at fixed time intervals ?
推荐答案
这种行为会使大多数OS内置的可爱机械短路,从而无法做到这一点,而cron之类的东西似乎是一个不错的选择.如果所有这些都失败(如果您只是想寻找一个快速的hacker选项),那么繁忙的等待并不是超级棒的事情,因为系统亮度不够高,无法超线程处理,因此您的程序在整个运行过程中吞噬了一个无能为力的核心您的程序,因此虽然很大程度上取决于品味,但我本人还是一个纳米睡眠的人.在nix/nux系统上:
This sort of behavior short-circuits the lovely machinery built in to most OSes to do just this, failing that something like cron would seem to be a lovely option. Failing all of that (if you're just looking for a quick hacky option) busy wait is not super awesome, the system isn't bright enough to hyperthread around that so your program winds up eating up a core doing nothing for the duration of your program, so while it's largely a matter of taste, I'm a nanosleep man myself. on nix/nux systems:
#include <time.h>
int main(void)
{
struct timespec sleepytime;
sleepytime.tv_sec = seconds_you_want_to_sleep
sleepytime.tv_nsec = nanoseconds_you_want_to_sleep
while( !done)
{
nanosleep(&sleepytime, NULL);
//do your stuff here
}
return 0;
}
如果您担心被中断,第二个参数应该是另一个timespec结构,该结构将存储剩余的时间量,请检查是否== 0,然后继续卡车.
if you're worried about getting interrupted, the second parameter should be another timespec struct, in which will be stored the amount of time remaining, check if == 0, then keep on trucking.
在Windows中显然要容易一些.
in windows apparently it is a little easier.
#include <windows.h>
int main(void)
{
while( !done)
{
Sleep(milliseconds_you_want_to_sleep);
//do your stuff here
}
return 0;
}
不幸的是,我没有运行Windows,所以我无法测试第二个代码示例.
Unfortunately I don't run windows so I haven't been able to test the second code sample.
这篇关于如何定期自动调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!