2011-01-30 65 views
1

我是C新手,並試圖找到一些代碼片段,以瞭解如何在C中實現時間觸發任務。我有兩個函數,其執行時間可能在50到200毫秒之間變化。我想將這些函數傳遞給一個工作線程,該工作線程應該計劃每500毫秒運行一次。在C(win32-platform)中是否有一個簡單的方法(如java的TimerTask)用標準運行時庫實現定時器任務?如何在win32平臺上以C語言實現時間驅動的任務?

回答

1

使用CreateTimerQueueTimer有窗口調用函數每500ms:

void CALLBACK timer_function(void* /*lpParameter*/,BOOLEAN /*TimerOrWaitFired*/) 
{ 
    /* do stuff */ 
} 


HANDLE timer_handle; 

void start_timer() 
{ 
    void* parameter; /* passed as lpParameter of timer_function */ 
    DWORD milliseconds_before_first_call=100; /* execute after 100ms */ 
    DWORD milliseconds_between_calls=500; /* and then every 500ms */ 
    CreateTimerQueueTimer(&timer_handle,NULL,timer_function,parameter, 
     milliseconds_before_first_call,milliseconds_between_calls, 
     WT_EXECUTELONGFUNCTION /* the function takes a while, and may block */ 
    ); 
}