English 中文(简体)
c++中是否有像 j一样的时间和时间?
原标题:Is there anything like timer and timertask in c++ just like java has?

I am not an experinced c++ programmer. So I just want to know how to implement timer and timertask just like java has in C++. I have tried timer_create example that is in man page of timer_create but It is not working as per my requirement. I want that after particualar time span an event should fire, and if specific condition fulfills then timer should be canceled.

Any help would be highly appreciated. Thanks, Yuvi.

最佳回答

这通常是一个非常棘手的问题,因为你必然要求进行某种同时处理,或至少是同步处理。

最简单、单一阅读的解决办法是使用波兹六条码。 这将使signal在规定时间之后送交你的处理。 您需要登记信号手(例如signal(2)),但受其所有限制(例如,你只能称手里的合成安全功能)。

A second, single-threaded option is to use a select-style (or epoll-style) I/O loop and use a kernel timer file descriptor. This is a very recent Linux feature, though, so availability will vary.

Finally, the typical, general solution is to use multiple threads: Make a dedicated thread for the timer whose only purpose is to sleep for the set time span and then execute some code. For this you will have to bear the full weight of concurrent programming responsibilities, such as handling shared data, guaranteeing the absence of races, etc.

一些高级图书馆,如Boost。 亚历杭德罗大学和新标准图书馆在你决定关闭多面通道后,提供一些冰雪时间机制。

问题回答

我也正在寻找像时事一样的 Java,但在我处理该问题时,我需要一个窗口C++。 在主要研究SO和学习通过班级成员的职能之后,我能够拿出一种似乎对我来说行之有效的解决办法。 我认识到,我回答这个问题已经过去了多年,但也许仍然寻求这一解决办法的人会认为这样做是有益的。

这是我通过视频演播室C++在Windows 10上测试的唯一窗户解决办法。 我仍在学习C++,因此,如果我打破任何规则,请听起来。 我认识到这些例外是最基本的,但很容易根据你们的需要加以调整。 我创建了一个类似于贾瓦语的时台。 你们需要从PierrTask语组学到一个新的用户级,并创建“任务”功能,包括你希望定期执行的代码。 The TimerTask上班:

--TimerTask.h--
#pragma once
#include <thread>

class TimerTask {
    HANDLE timeoutEvent;
    DWORD msTimeout;
    bool exit = false;
    void* pObj;

    static void taskWrapper(TimerTask* pObj) {
        while (!pObj->exit) {
            DWORD waitResult = WaitForSingleObject(pObj->timeoutEvent, pObj->msTimeout);
            if (pObj->exit)
                break;
            pObj->task();
        }
    }

public:

    TimerTask::TimerTask() {
        timeoutEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (!timeoutEvent) {
            throw "TimerTask CreateEvent Error: ";
        }
    }

    TimerTask::~TimerTask() {
        CloseHandle(timeoutEvent);
    }

    // Derived class must create task function that runs at every timer interval.
    virtual void task() = 0;

    void start(void* pObj, DWORD msTimeout) {
        this->pObj = pObj;
        this->msTimeout = msTimeout;

        std::thread timerThread(taskWrapper, (TimerTask*)pObj);
        timerThread.detach();
    }

    void stop() {
        exit = true;
        if (!SetEvent(timeoutEvent))
            throw "TimerTask:stop(): Error: ";
    }
};

这里是使用的实例。 就简便而言,我没有包括错误检查。

--Test.cpp--
#include "Windows.h"
#include <iostream>
#include "TimerTask.h"

using namespace std;

class KeepAliveTask : public TimerTask {
public:
    void task() {
        cout << "Insert your code here!
";
    }
};

int main()
{
    cout << "Hello, TimerTask!
";

    KeepAliveTask keepAlive;
    keepAlive.start(&keepAlive, 1000);  // Execute once per second

    Sleep(5100);    // Pause 5.1s to give time for task thread to run.
    keepAlive.stop();
    Sleep(1000);    // Pause another sec to give time for thread to stop.

    return 0;
}




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签