C语言在指定时间调用函数

C语言在指定时间调用函数,c,linux,timer,C,Linux,Timer,我使用以下C代码(linux ubuntu)每5分钟对代理服务器进行一次采样,并获得出价和要价: int main(int argc, char *argv[]) { struct stock myStock; struct stock *myStock_ptr; struct timeval t; time_t timeNow; strcpy(myStock.exchange,"MI"); strcpy(myStock.market,"EQCON"); strcpy(myStock.t3I

我使用以下C代码(linux ubuntu)每5分钟对代理服务器进行一次采样,并获得出价和要价:

int main(int argc, char *argv[])
{
struct stock myStock;
struct stock *myStock_ptr;
struct timeval t;
time_t timeNow;


strcpy(myStock.exchange,"MI");
strcpy(myStock.market,"EQCON");
strcpy(myStock.t3Id,"1");
strcpy(myStock.subscLabel,"");
strcpy(myStock.status,"0");
strcpy(myStock.ask,"");
strcpy(myStock.bid,"");

buildSubLabel(&myStock);

while (1) {
    t.tv_sec = 1;
    t.tv_usec = 0;

    select(0, NULL, NULL, NULL, &t);
    time(&timeNow);

    sample(&myStock);

    printf("DataLink on %s\n",myStock.subscLabel);
    printf("Time Now: --- %s",ctime(&timeNow));
    printf("DataLink Status---- %s\n",myStock.status);
    printf("Ask --- %s\n",myStock.ask);
    printf("Bid --- %s\n",myStock.bid);
    printf("###################\n");

}

return 0;
}
我不能做的是在特定时间安排示例函数。 我想在调用示例函数 9.01第一次 9.05第二次 9.10第三次 9.15 ...... 9.20 ...... 一直到17:30 17.30之后,该过程应终止

致意
Massimo

您应该使用线程在特定时间后调用所需的函数。
这样做:

#include <pthread.h>
#include <unistd.h> // for sleep() and usleep()

void *thread(void *arg) { // arguments not used in this case
    sleep(9); // wait 9 seconds
    usleep(10000) // wait 10000 microseconds (1000000s are 1 second)
    // thread has sleeped for 9.01 seconds
    function(); // call your function
    // add more here
    return NULL;
}

int main() {
    pthread_t pt;
    pthread_create(&pt, NULL, thread, NULL);
    // thread is running and will call function() after 9.01 seconds
}
#包括
#包括//用于sleep()和usleep()
void*thread(void*arg){//本例中未使用参数
睡眠(9);//等待9秒
usleep(10000)//等待10000微秒(1000000是1秒)
//线程已休眠9.01秒
function();//调用您的函数
//在这里添加更多
返回NULL;
}
int main(){
pthread_t pt;
pthread_创建(&pt,NULL,thread,NULL);
//线程正在运行,将在9.01秒后调用函数()
}
另一种方法是编写线程函数(通过检查程序运行的时间):

void*线程(void*arg){
while((clock()/(double)CLOCKS_PER_second)<9.01)//检查运行时间是否小于9.01秒
;
函数();
//等等。。。
返回NULL;
}
记住:必须链接pthread库!如果您使用gcc,这将是
-lpthread

有关pthreads(POSIX线程)的更多信息,请访问以下网站:

在时钟功能上:

完成处理后(即在
printf
之后),您需要计算延迟,因为处理需要时间。您也可以在17:30或更晚时结束循环


如果不减少延迟,则无法在一天中的正确时间获取样本。

我不确定您的最终目标,但可能更容易的事情是运行cron作业。Cron只是一个工具,它可以安排程序在特定时间运行。您可以将其设置为在一天中的特定时间内每五分钟运行一次程序。请参阅。非常感谢,corncob是我想知道是否可以使用某些linux系统调用来实现类似Excel/VBA onTime函数的最后一次机会。更新了我的答案:线程函数的一个变体,具有运行时间。因此我应该启动程序并计算时间(&timeNow)之间的秒(或毫秒)差上午9时01分。通过这种方式,我可以更新t.tv_sec(或t.tv_usec)等等
void *thread(void *arg) {
    while ((clock() / (double)CLOCKS_PER_SEC) < 9.01) // check the running time while it's less than 9.01 seconds
        ;
    function();
    // etc...
    return NULL;
}