简体   繁体   中英

How to use timer in c++ CodeBlock

K, hello everyone i am trying to make something like this :"Write a program that message on the computer screen to show how much time remains before the lesson end: if by the end of the lesson there is more than 30 minutes to be printed report something...", so i tried:

#include <iostream>
#include <cstdio>
#include <ctime>

using namespace std;
int main() {
    int startTime = 1, endTime;

    endTime = 30 * 3600;

    clock_t start = clock();


    cout<<"Time: "<< start <<'\n';

    if (start >= 7200)
    {
        // do something
    } else if (start == endTime)
    {
        // do something
    }
}

i want it to show time if time == number then do something. tried sleep(); but for some reason i got error in codeBlock.

I got "sleep was not declared in this scope." Try including the library that has it...

If you're in Unix, #include <unistd.h> .

If Windows, #include <windows.h> , then use Sleep() instead.

There's many ways to do that. here's 2 of them:

Using boost timer library this is better way:
http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/original_timer.html

Or start a thread

static const int INTERVAL_SEC = 60;
static void* thread_timer_process(void*)
{
    do 
    {
        // Do something;

        sleep(INTERVAL_SEC);

        // don't forget to put a cancel point in here

    } while(true);  
}

int main()
{
    pthread_t thread_id;
    thread_create(&thread_id, null, thread_timer_process,  NULL);

    // Other things

    pthread_cancel(thread_id);   // interrupt thread running.

    void *result = NULL;        
    pthread_join(thread_id, &result);  // wait for thread ending.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM