-1

I have a thread that i have created using pthread should be run exactly every minute . How can I do this in c program to run it every minute.sleep doent solve my problem .

Shayeeb Ahmed
  • 74
  • 1
  • 1
  • 16

1 Answers1

2

I'm assuming(a) you mean sleep is no good because if you sleep for 60 seconds following a seven-second job, that won't be every minute.

So, in order to go every minute regardless of how long the job takes, you can use something like (pseudo-code):

def threadFn():
    lastTime = now()  # or now() - 60 to run first one immediately.
    do forever:
        currTime = now()
        if currTime - lastTime >= 60:
            lastTime = currTime
            doPayload()
        sleep one second

This of course has the shortcoming that, if your job takes more than a minute, the next iteration of it will be delayed. But, short of having to handle multiple concurrent jobs, that's probably best.


(a) That seems the most likely possibility to me but it's an assumption I probably needn't have made if you'd included the code and/or added detail as to why it was a problem :-)

As another possibility, to ensure it only runs at hh:mm:00 (i.e., exactly on the minute switch-over), you could do a slight variation:

def threadFn():
    lastTime = now() - 1 # Ensure run at first hh:mm:00.
    do forever:
        currTime = now()
        currSec = getSecond(currTime) # using C's localtime()
        if currSec == 0 and currTime != lastTime:
            lastTime = currTime
            doPayload()
        sleep one tenth of a second

The reduced sleep is to ensure you run the payload as quickly as possible after entering the new minute.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • the thread is trying to post some data to re server .. so there may delay in that function .. regardless of that i need to post data exactly at next minute when the seconds hand of the clock turns 00. – Shayeeb Ahmed Nov 02 '17 at 06:18