Поделиться через


Функция SetSystemTimeAdjustmentPrecise (sysinfoapi.h)

Включает или отключает периодические корректировки времени для системных часов суток. Если этот параметр включен, такие корректировки времени можно использовать для синхронизации времени с некоторыми другими источниками информации о времени.

Синтаксис

BOOL SetSystemTimeAdjustmentPrecise(
  [in] DWORD64 dwTimeAdjustment,
  [in] BOOL    bTimeAdjustmentDisabled
);

Параметры

[in] dwTimeAdjustment

Предоставляет скорректированную частоту обновления часов.

[in] bTimeAdjustmentDisabled

Предоставляет флаг, указывающий режим корректировки времени, который будет использоваться системой.

Значение TRUE указывает, что система должна синхронизировать время суток с помощью собственных внутренних механизмов. В этом случае значение dwTimeAdjustment игнорируется.

Значение FALSE указывает, что приложение находится под контролем и что указанное значение dwTimeAdjustment добавляется к часам времени суток при каждом прерывании обновления часов.

Возвращаемое значение

Если функция выполняется успешно, возвращаемое значение не равно нулю.

Если функция выполняется неудачно, возвращается нулевое значение. Дополнительные сведения об ошибке можно получить, вызвав GetLastError. Одним из способов сбоя функции является то, что вызывающий объект не обладает привилегией SE_SYSTEMTIME_NAME.

Комментарии

Чтобы использовать эту функцию, вызывающий объект должен иметь права системного времени (SE_SYSTEMTIME_NAME). Эта привилегия отключена по умолчанию. Используйте функцию AdjustTokenPrivileges , чтобы включить привилегию перед вызовом этой функции, а затем отключите привилегию после вызова функции. Дополнительные сведения см. в примере кода ниже.

Примеры

В этом примере показано, как включить права системного времени, настроить системные часы с помощью Командлетов GetSystemTimeAdjustmentPrecise и SetSystemTimeAdjustmentPrecise, а также как аккуратно распечатать текущие корректировки системного времени.


/****************************************************************** 
* 
* ObtainRequiredPrivileges 
* 
* Enables system time adjustment privilege. 
* 
******************************************************************/ 
HRESULT 
ObtainRequiredPrivileges() 
{ 
    HRESULT hr; 
    HANDLE hProcToken = NULL; 
    TOKEN_PRIVILEGES tp = {0}; 
    LUID luid; 

    if (!LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &luid)) 
    { 
        hr = HRESULT_FROM_WIN32(GetLastError()); 
        printf("Failed to lookup privilege value. hr=0x%08x\n", hr); 
        return hr; 
    } 

    // get the token for our process 
    if (!OpenProcessToken(GetCurrentProcess(), 
    TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, 
    &hProcToken)) 
    { 
        hr = HRESULT_FROM_WIN32(GetLastError()); 
        printf("Failed to open process token. hr=0x%08x\n", hr); 
        return hr; 
    } 

    // Enable just the SYSTEMTIME privilege 
    tp.PrivilegeCount = 1; 
    tp.Privileges[0].Luid = luid; 
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 

    if (!AdjustTokenPrivileges(hProcToken, FALSE, &tp, 0, NULL, NULL)) 
    { 
        hr = HRESULT_FROM_WIN32(GetLastError()); 
        printf("Failed to adjust process token privileges. hr=0x%08x\n", hr); 
    } 
    else 
    { 
        hr = S_OK; 
        printf("Added SYSTEMTIME privilege to the process token\n"); 
    } 
    
    if (NULL != hProcToken) 
    { 
        CloseHandle(hProcToken); 
    } 
    return hr; 
} 

/****************************************************************** 
* 
* PrintCurrentClockAdjustments 
* 
* Prints current values of the system time adjustments. 
* 
******************************************************************/ 
void 
PrintCurrentClockAdjustments() 
{ 
    // More granular clock adjustments 
    DWORD64 ullCurrentAdjustment = 0; 
    DWORD64 ullTimeIncrement = 0; 
    BOOL bEnabledPrecise = 0; 
    HRESULT hrPrecise = S_OK; 

    // Legacy clock adjustments 
    DWORD dwCurrentAdjustment = 0; 
    DWORD dwTimeIncrement = 0; 
    BOOL bEnabled = 0; 
    HRESULT hr = S_OK; 

    if (!GetSystemTimeAdjustmentPrecise(&ullCurrentAdjustment, &ullTimeIncrement, &bEnabledPrecise)) 
    { 
        hrPrecise = HRESULT_FROM_WIN32(GetLastError()); 
    } 

    if (!GetSystemTimeAdjustment(&dwCurrentAdjustment, &dwTimeIncrement, &bEnabled)) 
    { 
        hr = HRESULT_FROM_WIN32(GetLastError()); 
    } 

    printf("Precise_ADJ:%I64u Precise_INCR:%I64u Precise_EN:%d Precise_hr:0x%08x ADJ:%u INCR:%u EN:%d hr:0x%08x\n", 
            ullCurrentAdjustment, ullTimeIncrement, bEnabledPrecise, hrPrecise, 
            dwCurrentAdjustment, dwTimeIncrement, bEnabled, hr); 
} 

/****************************************************************** 
* 
* RunNewAdjustmentSequence 
* 
* Adjust the system time using high-resolution 
* GetSystemTimeAdjustmentPrecise() and SetSystemTimeAdjustmentPrecise() API. 
* 
******************************************************************/ 
void 
RunNewAdjustmentSequence(DWORD dwPPMAdjustment) 
{ 
    DWORD64 ullCurrentAdjustment = 0; 
    DWORD64 ullTimeIncrement = 0; 
    BOOL bEnabledPrecise = 0; 
    LARGE_INTEGER liPerfCounterFrequency = {0}; 
    DWORD dwNewAdjustmentUnits; 
    const DWORD cMicroSecondsPerSecond = 1000000; 

    if (dwPPMAdjustment > 1000) 
    { 
        printf("Adjustment too large. Skipping new adjustment sequence.\n"); 
        return; 
    } 

    printf("Starting adjustment sequence using new API...\n"); 

    if (!GetSystemTimeAdjustmentPrecise(&ullCurrentAdjustment, &ullTimeIncrement, &bEnabledPrecise)) 
    { 
        printf("Failed to read the system time adjustment. Adjustment sequence aborted. hr:0x%08x\n", 
        HRESULT_FROM_WIN32(GetLastError())); 
        return; 
    } 

    (void)QueryPerformanceFrequency(&liPerfCounterFrequency); 
    printf("System Performance Counter Frequency: %I64u\n", 
    liPerfCounterFrequency.QuadPart); 


    dwNewAdjustmentUnits = (DWORD)(((float) dwPPMAdjustment * liPerfCounterFrequency.QuadPart/ cMicroSecondsPerSecond)); 

    printf("Adjusting the system clock by +%d PPM (+%d new units)\n", 
    dwPPMAdjustment, dwNewAdjustmentUnits); 

    if (!SetSystemTimeAdjustmentPrecise(ullCurrentAdjustment + dwNewAdjustmentUnits, FALSE)) 
    { 
        printf("Failed to set the system time adjustment. hr:0x%08x\n", 
        HRESULT_FROM_WIN32(GetLastError())); 
    } 

    PrintCurrentClockAdjustments(); 

    printf("Restoring system clock adjustment settings\n"); 

    if (!SetSystemTimeAdjustmentPrecise(ullCurrentAdjustment, FALSE)) 
    { 
        printf("Failed to set the system time adjustment. hr:0x%08x\n", 
        HRESULT_FROM_WIN32(GetLastError())); 
    } 

    PrintCurrentClockAdjustments(); 

    printf("Adjusting the system clock by -%d PPM (-%d new units)\n", 
    dwPPMAdjustment, dwNewAdjustmentUnits); 

    if (!SetSystemTimeAdjustmentPrecise(ullCurrentAdjustment - dwNewAdjustmentUnits, FALSE)) 
    { 
        printf("Failed to set the system time adjustment. hr:0x%08x\n", 
        HRESULT_FROM_WIN32(GetLastError())); 
    } 

    PrintCurrentClockAdjustments(); 

    printf("Restoring system clock adjustment settings\n"); 

    if (!SetSystemTimeAdjustmentPrecise(ullCurrentAdjustment, FALSE)) 
    { 
        printf("Failed to set the system time adjustment. hr:0x%08x\n", 
        HRESULT_FROM_WIN32(GetLastError())); 
    } 

    PrintCurrentClockAdjustments(); 

    printf("Adjustment sequence complete\n\n"); 
}

Требования

   
Минимальная версия клиента Windows 10 [только классические приложения]
Минимальная версия сервера Windows Server 2016 [только классические приложения]
Целевая платформа Windows
Header sysinfoapi.h
Библиотека Mincore.lib
DLL Api-ms-win-core-version-l1-2-3.dll

См. также раздел

GetSystemTimeAdjustmentPrecise