-1

I am working in a kind of "control block" that has to send a flag each 6 minutes. The thing is that I don't know if there is a simple way of doing this. I have had though in use clock_t inside a loop till it reaches the 6 minutes, and then call a method that sends the flag and re-initialize the clock_t variable.

I forgot to explain something, sleep is not an option because the block works like a flow, it has to send something the whole time. Actually the flag will change what is sending

Thanks in advance

xuandl
  • 183
  • 1
  • 2
  • 14

3 Answers3

1

You can just sleep the thread for 6 minutes and then send the flag:

for(;;)
{
    sendFlag();
    sleep(6*60);
}

Here are some options for the sleep method, including C++11's std::this_thread::sleep_for.

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Thanks for your answer. I forgot to explain something, sleep is not an option because the block works like a flow, it has to send something the whole time. Actually the flag will change what is sending – xuandl Jan 11 '13 at 16:01
  • @xuandl: Luchian's solution will not stop you doing that, as the sleep is running under a separate thread, but it does imply that you'll need to understand multi-threading and thread synchronization. It's not clear from your question whether you were anticipating that. – Component 10 Jan 11 '13 at 16:11
1

You could simply use a thread function that switches a flag on or off and sleep it for 6 minutes at a time. For example:

bool flag = false;

int main() {
    while(true) {
        if (flag == true) {
            flag = false;
        }
    }

    return(0);
}

void threadFunc() {
    flag = true;
    sleep(360); //360 seconds is 6 minutes
}

NOTE: You will need to use a mutex or semaphore because the code written now is not thread safe. How you use threads is also operating system dependent. Unless you use C++11 of course.

Kirk Backus
  • 4,776
  • 4
  • 32
  • 52
1

You don't need a whole thread just for this. Use a system OS periodic timer callback.

John
  • 7,301
  • 2
  • 16
  • 23