msalese
msalese

Reputation: 604

C -language calling a function at specified time

I'm using the following C code (linux ubuntu) to sample every 5 minutes the broker server and get the bid and ask value:

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

What I'm not able to do is to schedule the sample function at specific time. I'd like to call sample function at 9.01 the first time 9.05 the second time 9.10 the third time 9.15 ...... 9.20 ...... and so on until 17.30 After the 17.30 the process should terminate.

Best regards Massimo

Upvotes: 3

Views: 6303

Answers (2)

qwertz
qwertz

Reputation: 14792

You should use a thread to call the function you want after the specific time.
Do something like this:

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

An other way you can code the thread function (by checking the time your program is running):

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

Remember: You have to link the pthread library! If your using gcc this would be -lpthread.

For more information about pthreads (POSIX threads) you may look at this website:
https://computing.llnl.gov/tutorials/pthreads/
And on the clock function:
http://www.cplusplus.com/reference/clibrary/ctime/clock/

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 59997

After you have done the processing (i.e. after the printf stuff) you need to compute the delay, as the processing takes time. You can also end the loop when you reach 17:30 or later.

If you do not decrease the delay then you do not get the samples at the correct times throughout the day.

Upvotes: 0

Related Questions