如何在c++代码块中使用定时器

How to use timer in c++ CodeBlock

本文关键字:定时器 代码 c++      更新时间:2023-10-16

K,大家好,我正在试着做这样的东西:"写一个程序,在电脑屏幕上显示还有多少时间上课结束:如果在课程结束前还有超过30分钟的时间要打印报告……",于是我尝试了:

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

我想让它显示时间,如果时间==数字,然后做一些事情。试着睡();但是由于某些原因,我在codeBlock中出现了错误。

我得到"sleep未在此作用域中声明"。

如果是Unix系统,则为#include <unistd.h> .

如果Windows使用#include <windows.h>,则使用Sleep()

有很多方法可以做到。以下是其中的两个:

使用boost timer库是更好的方法:
http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/original_timer.html

或者启动一个线程

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