3

我正在使用以下 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 之后进程应该终止。

最好的问候马西莫

4

2 回答 2

2

您应该使用线程在特定时间后调用您想要的函数。
做这样的事情:

#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
}

编写线程函数的另一种方法(通过检查程序运行的时间):

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;
}

请记住:您必须链接 pthread 库!如果您使用 gcc 这将是-lpthread.

有关 pthreads(POSIX 线程)的更多信息,您可以查看此网站:
https
://computing.llnl.gov/tutorials/pthreads/ 关于时钟功能:
http ://www.cplusplus.com/reference/clibrary/ ctime/时钟/

于 2012-07-25T15:41:55.873 回答
0

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

如果您不减少延迟,那么您就不会在一天中的正确时间获得样品。

于 2012-07-25T15:46:50.840 回答