2013-09-26 32 views
2

下被要求同事和周圍的互聯網戳,並沒有找到一個很好的答案似乎像這裏一個很好的問題後:波科定時器實例

我使用POCO計時器在我的嵌入代碼(運行在Linux上)。計時器是Foundation組件的一部分。計時器具有三個基本功能:

Timer.start(); 
Timer.stop(); 
Timer.restart(); 

我試圖停下來,然後再重新啓動我的計時器,我無法得到它的工作......我看了所有的POCO樣品和示例,並沒有timer.restart()。

有沒有人有任何洞察到這一點,或有效的代碼示例停止和重新啓動定時器?即使回調函數沒有運行,計時器也會啓動並停止,但重新啓動似乎不起作用。

+0

系統允許多少個線程? –

回答

3

好吧,既然問了這個問題,我繼承了我的同事的項目,並且自己找到了答案。

//use restart for an already running timer, to restart it 
Timer.restart(); 

如果你的計時器已經停止並需要重新啓動,則需要先重置週期間隔,以下是與添加到我自己的幾行的波蘇例子。這編譯並重新啓動一個計時器。

#include "Poco/Timer.h" 
#include "Poco/Thread.h" 
#include "Poco/Stopwatch.h" 
#include <iostream> 


using Poco::Timer; 
using Poco::TimerCallback; 
using Poco::Thread; 
using Poco::Stopwatch; 


class TimerExample 
{ 
public: 
     TimerExample() 
     { 
       _sw.start(); 
     } 

     void onTimer(Timer& timer) 
     { 
       std::cout << "Callback called after " << _sw.elapsed()/1000 << "  milliseconds." << std::endl; 
     } 

private: 
     Stopwatch _sw; 
}; 


int main(int argc, char** argv) 
{  


    TimerExample example; 
    TimerCallback<TimerExample> callback(example, &TimerExample::onTimer); 

    Timer timer(250, 500); 

    timer.start(callback); 

    Thread::sleep(5000); 

    timer.stop(); 

    std::cout << "Trying to restart timer now" << std::endl; 

    timer.setStartInterval(250); 
    timer.setPeriodicInterval(500); 
    timer.start(callback); 

    Thread::sleep(5000); 

    timer.stop(); 


    return 0; 
}