/*void _USERENTRY LongThreadProc (LPVOID lParam) { while (longReference>0) { IMLOG("threadLONG"); CtrlEx->WMProcess(); SleepEx(500 , 1); } threadLong=0; } */ int StartLong(sDIALOG_long * sd) { // HANDLE timer; // if (dlg) { // timer = CreateWaitableTimer(0,0,0); // } else timer = timerLong; IMLOG("* Start Long %s" , (sd->flag & DLONG_BLOCKING)? "with non-BLOCKING.timer" : "Dlg w/o timer"); if (!K_CHECK_PTR(sd)) { IMDEBUG(DBG_ERROR, "Bad dLong pointer %x", sd); return 0; } LARGE_INTEGER lDueTime; if (sd->timeoutProc) { sd->timeoutProc(TIMEOUTT_START , sd); sd->timeoutHandle = CreateWaitableTimer(0,0,0); sd->timeoutPassed = 0; lDueTime.QuadPart = -10000 * TIMEOUT_INTERVAL; SetWaitableTimer(sd->timeoutHandle , &lDueTime , TIMEOUT_INTERVAL,TimeoutTimerProc, sd , 0); } if (sd->flag & DLONG_BLOCKING) { longReference++; lDueTime.QuadPart = 0; SetWaitableTimer(timerLong , &lDueTime , 50 ,LongTimerProc, sd?sd->handle:0 , 0); CtrlEx->WMProcess(); // if (!threadLong) threadLong=_beginthread(LongThreadProc,0,0); } return 1; }
void* freerds_client_thread(void* arg) { int fps; DWORD status; DWORD nCount; HANDLE events[8]; HANDLE PackTimer; LARGE_INTEGER due; rdsBackendConnector* connector = (rdsBackendConnector*) arg; fps = connector->fps; PackTimer = CreateWaitableTimer(NULL, TRUE, NULL); due.QuadPart = 0; SetWaitableTimer(PackTimer, &due, 1000 / fps, NULL, NULL, 0); nCount = 0; events[nCount++] = PackTimer; events[nCount++] = connector->StopEvent; events[nCount++] = connector->hClientPipe; while (1) { status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); if (WaitForSingleObject(connector->StopEvent, 0) == WAIT_OBJECT_0) { break; } if (WaitForSingleObject(connector->hClientPipe, 0) == WAIT_OBJECT_0) { if (freerds_transport_receive((rdsBackend*) connector) < 0) break; } if (status == WAIT_OBJECT_0) { freerds_message_server_queue_pack(connector); if (connector->fps != fps) { fps = connector->fps; due.QuadPart = 0; SetWaitableTimer(PackTimer, &due, 1000 / fps, NULL, NULL, 0); } } } CloseHandle(PackTimer); return NULL; }
static int systimer_create(systimer_t* id, unsigned int period, int oneshot, systimer_proc callback, void* cbparam) { LARGE_INTEGER tv; timer_context_t* ctx; ctx = (timer_context_t*)malloc(sizeof(timer_context_t)); if(!ctx) return -ENOMEM; memset(ctx, 0, sizeof(timer_context_t)); ctx->callback = callback; ctx->cbparam = cbparam; ctx->timerId = CreateWaitableTimer(NULL, FALSE, NULL); if(0 == ctx->timerId) { free(ctx); return -(int)GetLastError(); } tv.QuadPart = -10000L * period; // in 100 nanosecond intervals if(!SetWaitableTimer(ctx->timerId, &tv, oneshot?0:period, timer_schd_worker, ctx, FALSE)) { CloseHandle(ctx->timerId); free(ctx); return -(int)GetLastError(); } *id = (systimer_t)ctx; return 0; }
static void do_replay(void) { HDC dc; struct timeval delay; LARGE_INTEGER del; again: if (play_state!=2) { set_buttons(0); CancelWaitableTimer(timer); return; } EnterCriticalSection(&vt_mutex); replay_play(&delay); draw_size(); dc=GetDC(termwnd); draw_vt(dc, chx*vt->sx, chy*vt->sy, vt); ReleaseDC(termwnd, dc); LeaveCriticalSection(&vt_mutex); set_prog(); if (play_state!=2) { set_buttons(1); // finished return; } del.QuadPart=delay.tv_sec; del.QuadPart*=1000000; del.QuadPart+=delay.tv_usec; if (del.QuadPart<=0) goto again; del.QuadPart*=-10; SetWaitableTimer(timer, &del, 0, 0, 0, 0); set_buttons(0); }
//--------------------------------------------------------------------------- void __TROPICALL BTP_Tempo::AlterarAtivo(bool temp) throw(BTP_Excecao*) { if(temp) { LARGE_INTEGER Preset; Preset.QuadPart=-(intervalo*10000); int temp1=0; if(!manual)temp1=intervalo; if(!SetWaitableTimer(htimer,&Preset,temp1,NULL,NULL,false)) { throw new BTP_Excecao(this, "Erro iniciar o Temporizador"); } ativo=true; } else { if(!CancelWaitableTimer(htimer)) { throw new BTP_Excecao(this, "Erro ao parar o temporizador"); } ativo=false; } }
bool Condition::wait(UniqueLock<honey::Mutex>& external, honey::MonoClock::TimePoint time) { auto _ = ScopeGuard(lock::lockGuard(external)); _waitLock->lock(); ++_waitCount; _waitLock->unlock(); //Wait for both the semaphore and the high resolution timeout HANDLE handles[2] = { _sema }; int handleCount = 1; if (time != honey::MonoClock::TimePoint::max()) { //Convert to windows 100 nanosecond period, negative time means relative LARGE_INTEGER sleepTime; sleepTime.QuadPart = (-Alge::max(time - honey::MonoClock::now(), honey::MonoClock::Duration::zero()) / 100).count(); verify(SetWaitableTimer(_timer, &sleepTime, 0, NULL, NULL, 0)); handles[handleCount++] = _timer; } //Unfair but safe race condition: external unlock and wait should be atomic external.unlock(); DWORD res = WaitForMultipleObjects(handleCount, handles, FALSE, INFINITE); _waitLock->lock(); --_waitCount; bool lastWait = _broadcast && _waitCount == 0; _waitLock->unlock(); //Unfair but safe race condition: wait done signal and external relock should be atomic if (lastWait) SetEvent(_waitDone); return res == WAIT_OBJECT_0; } //external.lock()
//------------------------------------------------------------------------------ static void callTimerCb(UINT index_p) { tHresTimerInfo* pTimerInfo; // Get the timer info according to the index pTimerInfo = &hresTimerInstance_l.aTimerInfo[index_p]; // Check if the timer is a periodic timer if (pTimerInfo->dueTime.QuadPart != 0) { HANDLE hTimer; BOOL fRet; // Set up the timer again hTimer = hresTimerInstance_l.aHandle[index_p + HRTIMER_HDL_TIMER0]; fRet = SetWaitableTimer(hTimer, &pTimerInfo->dueTime, 0L, NULL, NULL, 0); if (!fRet) { DEBUG_LVL_ERROR_TRACE("SetWaitableTimer failed (%d)\n", GetLastError()); return; } } // If a callback function is given, call it if (pTimerInfo->pfnCallback != NULL) { pTimerInfo->pfnCallback(&pTimerInfo->eventArg); } }
int evfilt_timer_knote_create(struct filter *filt, struct knote *kn) { HANDLE th; LARGE_INTEGER liDueTime; kn->kev.flags |= EV_CLEAR; th = CreateWaitableTimer(NULL, FALSE, NULL); if (th == NULL) { dbg_lasterror("CreateWaitableTimer()"); return (-1); } dbg_printf("created timer handle %p", th); convert_msec_to_filetime(&liDueTime, kn->kev.data); // XXX-FIXME add completion routine to this call if (!SetWaitableTimer(th, &liDueTime, (LONG)( (kn->kev.flags & EV_ONESHOT) ? 0 : kn->kev.data ), NULL, NULL, FALSE)) { dbg_lasterror("SetWaitableTimer()"); CloseHandle(th); return (-1); } kn->data.handle = th; RegisterWaitForSingleObject(&kn->kn_event_whandle, th, evfilt_timer_callback, kn, INFINITE, 0); knote_retain(kn); return (0); }
void CALLBACK timerCallback(LPVOID lpArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue) { LARGE_INTEGER period = { 0, }; period.QuadPart = -160000; TimerArg* schedulerArg = (TimerArg*)lpArgToCompletionRoutine; schedulerArg->ref_count -= 1; TimerContext* context = new TimerContext(); context->gameRoomId = schedulerArg->room_id; /* for (int i = 0; i < schedulerArg->ref_count; ++i) printf("@"); puts(""); */ if (GameRoomManager::getInstance()->getGameRoom(schedulerArg->room_id)) { PostQueuedCompletionStatus(Scheduler::hCompletionPort, 0, CKT_TIMER, (LPOVERLAPPED)context); // schedulerArg->tick = timeGetTime(); // SetWaitableTimer(schedulerArg->timer, &period, 16, timerCallback, lpArgToCompletionRoutine, TRUE); schedulerArg->ref_count += 1; SetWaitableTimer(schedulerArg->timer, &period, 0, timerCallback, lpArgToCompletionRoutine, TRUE); } else if (schedulerArg->ref_count == 0) { CloseHandle(schedulerArg->timer); SAFE_DELETE(schedulerArg); } }
/* procedure to poll the event queue for timer events, run by the clock thread; on a timer event, call "send_interrupt()" to run the system thread's clock handler routine */ DWORD WINAPI clock_poll(LPVOID arg) { #ifdef WINCE for(;;) { Sleep(PERIOD/1000); /* sleep requires time in milliseconds */ send_interrupt(CLOCK_INTERRUPT_TYPE, NULL); } #else LARGE_INTEGER i; HANDLE timer; /* HANDLE thread = GetCurrentThread(); */ char name[64]; sprintf(name, "timer %d", pid); timer = CreateWaitableTimer(NULL, TRUE, name); assert(timer != NULL); for (;;) { i.QuadPart = -PERIOD*10; /* NT timer values are in hundreds of nanoseconds */ AbortOnError(SetWaitableTimer(timer, &i, 0, NULL, NULL, FALSE)); if (WaitForSingleObject(timer, INFINITE) == WAIT_OBJECT_0) { if (DEBUG) kprintf("CLK: clock tick.\n"); send_interrupt(CLOCK_INTERRUPT_TYPE, NULL); } } #endif /* never reached */ return 0; }
//------------------------------------------------------------------------------------------------- extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE hInstDll, DWORD fdwReason, LPVOID) { if (fdwReason == DLL_PROCESS_ATTACH) { const DWORD dwLen = GetModuleFileNameW(nullptr, g_wBuf, MAX_PATH+1); if (dwLen >= 6 && dwLen < MAX_PATH) { wchar_t *pDelim = g_wBuf+dwLen; do { if (*--pDelim == L'\\') break; } while (pDelim > g_wBuf); if (pDelim >= g_wBuf+4 && pDelim <= g_wBuf+MAX_PATH-g_dwPathMargin && (pDelim[1] = L'\0', SetCurrentDirectoryW(g_wBuf)) && DisableThreadLibraryCalls(hInstDll)) if (const HANDLE hTimer = CreateWaitableTimerW(nullptr, FALSE, nullptr)) { LARGE_INTEGER liDueTime; liDueTime.QuadPart = 0; const bool bOk = SetWaitableTimer(hTimer, &liDueTime, 0, TimerAPCProc, hInstDll, FALSE); if (CloseHandle(hTimer) && bOk) { *pDelim = L'\0'; return TRUE; } } } } return FALSE; }
void BalloonMgr::post() { if (_pending.empty()) return; // No active balloon!? // Post balloon tip Balloon &balloon = _pending.front(); NOTIFYICONDATA nid; nid.hWnd = balloon.hwnd; nid.cbSize = sizeof(nid); nid.uID = IDI_APCUPSD; nid.uFlags = NIF_INFO; astrncpy(nid.szInfo, balloon.text.c_str(), sizeof(nid.szInfo)); astrncpy(nid.szInfoTitle, balloon.title.c_str(), sizeof(nid.szInfoTitle)); nid.uTimeout = MAX_TIMEOUT; nid.dwInfoFlags = NIIF_INFO; Shell_NotifyIcon(NIM_MODIFY, &nid); // Set a timeout to clear the balloon LARGE_INTEGER timeout; if (_pending.size() > 1) // More balloons pending: use minimum timeout timeout.QuadPart = -(MIN_TIMEOUT * 10000); else // No other balloons pending: Use maximum timeout timeout.QuadPart = -(MAX_TIMEOUT * 10000); SetWaitableTimer(_timer, &timeout, 0, NULL, NULL, false); // Remember the time at which we started the timer gettimeofday(&_time, NULL); }
void throttle_restart() { /* This can't be a restart if the service is already running. */ if (! throttle++) return; int ms = throttle_milliseconds(); if (throttle > 7) throttle = 8; char threshold[8], milliseconds[8]; _snprintf(threshold, sizeof(threshold), "%d", throttle_delay); _snprintf(milliseconds, sizeof(milliseconds), "%d", ms); log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service_name, threshold, milliseconds, 0); if (throttle_timer) { ZeroMemory(&throttle_duetime, sizeof(throttle_duetime)); throttle_duetime.QuadPart = 0 - (ms * 10000LL); SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0); } service_status.dwCurrentState = SERVICE_PAUSED; SetServiceStatus(service_handle, &service_status); if (throttle_timer) WaitForSingleObject(throttle_timer, INFINITE); else Sleep(ms); }
/* Service control handler */ unsigned long WINAPI service_control_handler(unsigned long control, unsigned long event, void *data, void *context) { switch (control) { case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_STOP: log_service_control(service_name, control, true); stop_service(0, true, true); return NO_ERROR; case SERVICE_CONTROL_CONTINUE: log_service_control(service_name, control, true); if (! throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED; throttle = 0; ZeroMemory(&throttle_duetime, sizeof(throttle_duetime)); SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0); service_status.dwCurrentState = SERVICE_CONTINUE_PENDING; service_status.dwWaitHint = throttle_milliseconds() + NSSM_WAITHINT_MARGIN; log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service_name, 0); SetServiceStatus(service_handle, &service_status); return NO_ERROR; case SERVICE_CONTROL_PAUSE: /* We don't accept pause messages but it isn't possible to register only for continue messages so we have to handle this case. */ log_service_control(service_name, control, false); return ERROR_CALL_NOT_IMPLEMENTED; } /* Unknown control */ log_service_control(service_name, control, false); return ERROR_CALL_NOT_IMPLEMENTED; }
void P_SEND_Timer_IMPL(PRT_MACHINEINST *context, PRT_VALUE *evnt, PRT_VALUE *payload, PRT_BOOLEAN doTransfer) { printf("Entering P_SEND_Timer_IMPL\n"); PRT_VALUE *ev; BOOL success; TimerContext *timerContext = (TimerContext *)context->extContext; if (!inStart && evnt->valueUnion.ev == P_EVENT_START) { printf("Timer received START\n"); LARGE_INTEGER liDueTime; liDueTime.QuadPart = -10000 * payload->valueUnion.nt; success = SetWaitableTimer(timerContext->timer, &liDueTime, 0, Callback, context, FALSE); inStart = TRUE; PrtAssert(success, "SetWaitableTimer failed"); } else if (evnt->valueUnion.ev == P_EVENT_CANCEL) { printf("Timer received CANCEL\n"); inStart = FALSE; success = CancelWaitableTimer(timerContext->timer); if (success) { ev = PrtMkEventValue(P_EVENT_CANCEL_SUCCESS); PrtSend(context, PrtGetMachine(context->process, timerContext->client), ev, context->id, PRT_FALSE); } else { ev = PrtMkEventValue(P_EVENT_CANCEL_FAILURE); PrtSend(context, PrtGetMachine(context->process, timerContext->client), ev, context->id, PRT_FALSE); } PrtFreeValue(ev); } else { PrtAssert(FALSE, "Illegal event"); } }
void main(void) { const int nTimerUnitsPerSecond = 10000000; int cAbrasionCount = 0; SYSTEMTIME st; LARGE_INTEGER li; HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL); GetLocalTime(&st); printf("Start time: \t\t%.2d:%.2d:%.2d\n\n", st.wHour, st.wMinute, st.wSecond); li.QuadPart = -(15 * nTimerUnitsPerSecond); if (SetWaitableTimer(hTimer, &li, 15 * 1000, NULL, NULL, FALSE)){ while (TRUE){ GetLocalTime(&st); cAbrasionCount++; printf("%d.Timer abrasion: \t%.2d:%.2d:%.2d\n", cAbrasionCount, st.wHour, st.wMinute, st.wSecond); hSecThread = CreateThread(NULL, 0, ThreadFunc1, (LPVOID)cAbrasionCount, 0, &dwSecThreadId); DWORD dw = WaitForSingleObject(hTimer, INFINITE); TerminateThread(hSecThread, 1001); hSecThread = NULL; dwSecThreadId = 0; } } }
/* set the timer rate; called in the polling thread context */ static void CALLBACK set_timer_rate( ULONG_PTR arg ) { LARGE_INTEGER when; when.u.LowPart = when.u.HighPart = 0; SetWaitableTimer( VGA_timer, &when, arg, VGA_Poll, 0, FALSE ); }
void CRealTimer::DoTimer() { CBenchmark bm; float Error = 0; float Period = 1.0f / m_Freq; int PrevReset = 0; UINT Clock = 0; HANDLE ha[2] = {m_Event, m_Timer}; while (m_State != DIE) { __int64 Due = round((Period - Error) * -1e7); // relative UTC SetWaitableTimer(m_Timer, (LARGE_INTEGER *)&Due, 0, NULL, NULL, 0); WaitForMultipleObjects(m_State + 1, ha, FALSE, INFINITE); m_State = m_NewState; if (m_State == RUN) { m_Callback(m_Cookie); Clock++; Error = float(bm.Elapsed() - Clock * Period); if (m_Reset != PrevReset) { Period = 1.0f / m_Freq; PrevReset = m_Reset; Clock = 0; Error = 0; bm.Reset(); } } } }
void TRI_usleep(unsigned long waitTime) { int result; HANDLE hTimer = NULL; // stores the handle of the timer object LARGE_INTEGER wTime; // essentially a 64bit number wTime.QuadPart = waitTime * 10; // *10 to change to microseconds wTime.QuadPart = -wTime.QuadPart; // negative indicates relative time elapsed, // Create an unnamed waitable timer. hTimer = CreateWaitableTimer(NULL, 1, NULL); if (hTimer == NULL) { // no much we can do at this low level return; } if (GetLastError() == ERROR_ALREADY_EXISTS) { abort(); } // Set timer to wait for indicated micro seconds. if (!SetWaitableTimer(hTimer, &wTime, 0, NULL, NULL, 0)) { // no much we can do at this low level return; } // Wait for the timer result = WaitForSingleObject(hTimer, INFINITE); if (result != WAIT_OBJECT_0) { abort(); } CloseHandle(hTimer); // todo: go through what the result is e.g. WAIT_OBJECT_0 return; }
int select123(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timeval *timeout) { if(readfds == NULL && writefds == NULL && exceptfds == NULL) { // is this highest-res? LARGE_INTEGER liDueTime; liDueTime.QuadPart = -(LONGLONG)(timeout->tv_sec*1e7 + timeout->tv_usec*10); // Set a timer to wait if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0)) { printf("SetWaitableTimer failed (%d)\n", GetLastError()); return -1; } // Wait for the timer. if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0) printf("WaitForSingleObject failed (%d)\n", GetLastError()); return 0; } else { return select(nfds, readfds, writefds, exceptfds, timeout); } }
void start_benchmark(struct benchmark_st * st) { memset(st, 0, sizeof(*st)); #ifndef _WIN32 st->old_handler = signal (SIGALRM, alarm_handler); #endif gettime (&st->start); benchmark_must_finish = 0; #if defined(_WIN32) st->wtimer = CreateWaitableTimer (NULL, TRUE, NULL); if (st->wtimer == NULL) { fprintf (stderr, "error: CreateWaitableTimer %u\n", GetLastError ()); exit(1); } st->wthread = CreateThread (NULL, 0, alarm_handler, &st->wtimer, 0, NULL); if (st->wthread == NULL) { fprintf (stderr, "error: CreateThread %u\n", GetLastError ()); exit(1); } st->alarm_timeout.QuadPart = (BSECS) * 10000000; if (SetWaitableTimer (st->wtimer, &st->alarm_timeout, 0, NULL, NULL, FALSE) == 0) { fprintf (stderr, "error: SetWaitableTimer %u\n", GetLastError ()); exit(1); } #else alarm (BSECS); #endif }
static void newhandler_08_timer_thread(void) { LARGE_INTEGER DueTime; //char sout[100]; if(!int08_timer_handle){ int08_timer_handle=CreateWaitableTimer(NULL,0,NULL); if(int08_timer_handle){ DueTime.QuadPart=-(int08_timer_period*10000); SetWaitableTimer(int08_timer_handle,&DueTime,(int08_timer_period+1)/2,NULL,NULL,0); }else{ } } do{ funcbit_smp_value_increment(int08counter); //sprintf(sout,"c:%5d tp:%d",int08counter,int08_timer_period); //display_message(1,0,sout); WaitForSingleObject(int08_timer_handle,int08_timer_period); }while(mpxplay_timed_functions); if(int08_timer_handle){ CancelWaitableTimer(int08_timer_handle); CloseHandle(int08_timer_handle); int08_timer_handle=NULL; } }
void Delay::waitNsec(uint64_t nsec) { // POSIX. #if defined(DUNE_SYS_HAS_CLOCK_NANOSLEEP) || defined(DUNE_SYS_HAS_NANOSLEEP) timespec ts; ts.tv_sec = nsec / c_nsec_per_sec; ts.tv_nsec = nsec - (ts.tv_sec * c_nsec_per_sec); # if defined(DUNE_SYS_HAS_CLOCK_NANOSLEEP) clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, 0); # else nanosleep(&ts, 0); # endif // Microsoft Windows. #elif defined(DUNE_SYS_HAS_CREATE_WAITABLE_TIMER) HANDLE t = CreateWaitableTimer(0, TRUE, 0); LARGE_INTEGER dl; dl.QuadPart = (uint64_t)nsec / 100; // Negative value means relative time. dl.QuadPart *= -1; SetWaitableTimer(t, &dl, 0, 0, 0, 0); WaitForSingleObject(t, INFINITE); CloseHandle(t); // Unsupported system. #else # error Delay::waitNsec() is not yet implemented in this system #endif }
//设置好相关参数(上传文件的FTP信息,上传文件的时间设置)之后,开始执行设置的定时任务 BOOL FtpConnecter::startUploadTask() { SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = NULL; DWORD id; //设置FTP信息 m_FtpInfo._hWaitableTimer = CreateWaitableTimer(&sa, FALSE, NULL); if (m_FtpInfo._hWaitableTimer == NULL) return FALSE; m_FtpInfo._strFolderPath = getRemoteFolderPath(); m_hWorkThread = CreateThread(&sa, 0, UploadeFile, (LPVOID)&m_FtpInfo, 0, &id); if (m_hWorkThread == NULL) { CString strErr = GlobalFunc::formatErrorCode(GetLastError()); strErr = _T("启动上传任务失败,上传文件线程未启动") + strErr; pushTrackInfo(strErr); return FALSE; } SetWaitableTimer(m_FtpInfo._hWaitableTimer, &m_liBeginTime, m_lTimePeriod, NULL, NULL, TRUE);//支持唤醒计算机<TRUE> //CloseHandle(m_FtpInfo._hWaitableTimer);//在本对象析构的时候才关闭这个句柄 return TRUE; }
void usleep(__int64 waitTime) { if (waitTime > 0) { if (waitTime > 100) { // use a waitable timer for larger intervals > 0.1ms HANDLE timer; LARGE_INTEGER ft; ft.QuadPart = -(10*waitTime); // Convert to 100 nanosecond interval, negative value indicates relative time timer = CreateWaitableTimer(NULL, TRUE, NULL); SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0); WaitForSingleObject(timer, INFINITE); CloseHandle(timer); } else { // use a polling loop for short intervals <= 100ms LARGE_INTEGER perfCnt, start, now; __int64 elapsed; QueryPerformanceFrequency(&perfCnt); QueryPerformanceCounter(&start); do { QueryPerformanceCounter((LARGE_INTEGER*) &now); elapsed = (__int64)((now.QuadPart - start.QuadPart) / (float)perfCnt.QuadPart * 1000 * 1000); } while ( elapsed < waitTime ); } } }
int TestSynchWaitableTimerAPC(int argc, char* argv[]) { HANDLE hTimer; BOOL bSuccess; LARGE_INTEGER due; APC_DATA* apcData; apcData = (APC_DATA*) malloc(sizeof(APC_DATA)); g_Event = CreateEvent(NULL, TRUE, FALSE, NULL); hTimer = CreateWaitableTimer(NULL, FALSE, NULL); if (!hTimer) return -1; due.QuadPart = -15000000LL; /* 1.5 seconds */ apcData->StartTime = GetTickCount(); bSuccess = SetWaitableTimer(hTimer, &due, 2000, TimerAPCProc, apcData, FALSE); if (!bSuccess) return -1; if (WaitForSingleObject(g_Event, INFINITE) != WAIT_OBJECT_0) { printf("WaitForSingleObject failed (%d)\n", GetLastError()); return -1; } CloseHandle(hTimer); CloseHandle(g_Event); free(apcData); return 0; }
int main() { HANDLE hTimer = NULL; LARGE_INTEGER liDueTime; // рт100дицКн╙╥ж╦Н liDueTime.QuadPart = -100000000LL; // Create an unnamed waitable timer. hTimer = CreateWaitableTimer(NULL, TRUE, NULL); if (NULL == hTimer) { printf("CreateWaitableTimer failed (%d)\n", GetLastError()); return 1; } printf("Waiting for 10 seconds...\n"); // Set a timer to wait for 10 seconds. if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0)) { printf("SetWaitableTimer failed (%d)\n", GetLastError()); return 2; } // Wait for the timer. if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0) { printf("WaitForSingleObject failed (%d)\n", GetLastError()); } else { printf("Timer was signaled.\n"); } system("pause"); return 0; }
/** * Async callback. * * @param lpArgToCompletionRoutine Pointer to our timer structure. */ VOID CALLBACK rttimerAPCProc(LPVOID lpArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue) { PRTTIMER pTimer = (PRTTIMER)lpArgToCompletionRoutine; /* * Check if we're begin destroyed. */ if (pTimer->u32Magic != RTTIMER_MAGIC) return; /* * Callback the handler. */ pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pTimer->iTick); /* * Rearm the timer handler. */ #ifdef USE_CATCH_UP pTimer->llNext.QuadPart += (int64_t)pTimer->uMilliesInterval * 10000; LARGE_INTEGER ll; ll.QuadPart = RTTimeNanoTS() - pTimer->llNext.QuadPart; if (ll.QuadPart < -500000) ll.QuadPart = ll.QuadPart / 100; else ll.QuadPart = -500000 / 100; /* need to catch up, do a minimum wait of 0.5ms. */ #else LARGE_INTEGER ll = pTimer->llNext; #endif BOOL frc = SetWaitableTimer(pTimer->hTimer, &ll, 0, rttimerAPCProc, pTimer, FALSE); AssertMsg(frc || pTimer->u32Magic != RTTIMER_MAGIC, ("last error %d\n", GetLastError())); }
HOOKFUNC BOOL WINAPI MySetWaitableTimer(HANDLE hTimer, const LARGE_INTEGER *lpDueTime, LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, BOOL fResume) { ENTER(); BOOL rv = SetWaitableTimer(hTimer, lpDueTime, lPeriod, pfnCompletionRoutine, lpArgToCompletionRoutine, fResume); LEAVE(rv); return rv; }
unsigned __stdcall ManageThread( void* Param ) { HANDLE hGlobal = CreateWaitableTimer( NULL, FALSE, L"ZZVBN-ARARA-12" ); //Global DB update timer HANDLE hLocal = CreateWaitableTimer( NULL, FALSE, L"ZZVBN-ARARA-36" ); //Local DB update timer //--------------------------------------------------------- LARGE_INTEGER liGlobalUpd; LARGE_INTEGER liLocalUpd; const int nTimeUnits = 10000000; liGlobalUpd.QuadPart = -( 60/*1 hour*/ * nTimeUnits ); liLocalUpd.QuadPart = -( 10/*5 minutes*/ * nTimeUnits ); //--------------------------------------------------------- //set timers here, for global and local updates SetWaitableTimer( hGlobal, &liGlobalUpd, 60/*1 hour*/ * 1000, NULL, NULL, FALSE ); SetWaitableTimer( hLocal, &liLocalUpd, 10/*5 minutes*/ *1000, NULL, NULL, FALSE ); //--------------------------------------------------------- while( true ) { //capture critical section and free it every 5 minutes, so Local Update Thread can update values EnterCriticalSection( &csUpdater ); bInitiated = true; WaitForSingleObject( hLocal, INFINITE ); LeaveCriticalSection( &csUpdater ); Sleep( 200 ); } return 0; }