【问题标题】:Windows API to trigger the time synchronizationWindows API 触发时间同步
【发布时间】:2011-02-15 20:31:59
【问题描述】:
是否有 Windows API 可以实现相当于单击“日期和时间属性”/“Internet 时间”选项卡中的“立即更新”按钮(通过双击任务栏中的时钟打开)?
有没有办法监控windows什么时候触发时间同步,什么时候触发成功或者失败?
【问题讨论】:
标签:
windows
time
synchronization
ntp
【解决方案1】:
这似乎有效:
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();
}
}
}
它没有记录,所以我不确定可能的标志是什么,但 8 似乎可以很好地完成这项工作 - 使用我的系统时钟进行了测试。如果您运行的是 64 位 Windows,请编译为 64 位,否则您将遇到访问冲突异常。
W32TimeQueryStatus应该可以得到最后一次成功同步的时间。当我有更多时间时,我会继续努力。
【解决方案2】:
时间服务没有公开API,但要触发时间同步,您可以使用w32tm 命令行工具。
在 C/C++ 中,您可以执行以下操作:
include <process.h>
...
system("w32tm /resync /nowait");
查看w32tm documentation 了解更多选项。