Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows API to trigger the time synchronization

Is there a windows API that would achieve the equivalent of clicking the "Update now" button in the "Date and time properties"/"Internet time" tab (opened by double clicking the clock in the taskbar)?

Is there a way to monitor when the time synchronization is triggered by windows and when it succeeds or fails?

like image 232
Hrvoje Prgeša Avatar asked May 05 '10 09:05

Hrvoje Prgeša


People also ask

How do I get Windows to automatically sync time?

The easiest way to synchronize your clock is to use Windows 10's settings. Open the Start menu and click Settings. Then, click Time & Language on the Settings dialog box. Scroll down to the Related settings section and click Additional date, time, & regional settings.

How do I schedule synchronize time?

Go to > Start and type > Task Scheduler in the search field, then open the respective result. Within the Task Scheduler Library on the left hand side, click through to the > Microsoft > Windows > Time Synchronization branch and click > Create Task in the menu on the right hand side.

How does Active Directory know time is synced?

To determine if a domain member is configured for domain time sync, examine the REG_SZ value at HKLM\System\CurrentControlSet\Services\W32Time\Parameters\Type. If it is set to "Nt5DS" then the computer is synchronizing time with the Active Directory time hierarchy.


2 Answers

There is no API exposed by the time service, but to trigger a time synchronization you can use the w32tm command line tool.

In C/C++ you can do something like this:

include <process.h>

...

system("w32tm /resync /nowait");

Take a look at w32tm documentation for further options.

like image 199
Frank Bollack Avatar answered Sep 21 '22 17:09

Frank Bollack


This seems to work:

using System;
using System.Runtime.InteropServices;

namespace ClockResync
{
    class Program
    {
        [DllImport("w32time.dll")]
        public static extern uint W32TimeSyncNow([MarshalAs(UnmanagedType.LPWStr)]String computername, bool wait, uint flag);
        static void Main(string[] args)
        {
            Console.WriteLine(W32TimeSyncNow("computername", true, 8).ToString());
            Console.ReadLine();
        }
    }
}

It's undocumented so I'm not exactly sure what the possible flags are, but 8 seems to do the job just fine - tested with my system clock. If you're running Windows 64-bit, compile for 64-bit or you'll be getting access violation exceptions.

W32TimeQueryStatus should be able to get the last successful sync time. I'll work on that when I have more time.

like image 43
Michał Masny Avatar answered Sep 19 '22 17:09

Michał Masny