cat articles/wsl-clock-sync
Fixing WSL clock drift after sleep from the Windows side
After developing in a WSL2 environment for the first time in a while, I noticed that the time was off. A problem I had not seen before seemed to have appeared: the WSL clock drifted after waking from sleep.
This is an old issue, and it was fixed in yesterday's Insider Preview Linux kernel, so it will probably be fixed in Windows 10 21H1. At the moment, though, the problem still occurs.
On the Linux side, hwclock --hctosys fixes it. But running that command manually every time is annoying, and setting up periodic execution inside WSL2, for example with cron.d, is more troublesome than it first looks. So I prepared a batch file that runs the WSL-side command from Windows, then ran it from Windows Task Scheduler.
wsl.exe -u root --exec /usr/sbin/hwclock --hctosys
There are several examples online for running a Task Scheduler job when the machine wakes from sleep, so I will skip that part. This solved the issue. After writing that much, I found a comment on the issue that does the same thing in one line.
schtasks /Create /TN wsl-clock /TR "wsl.exe -u root sh -c hwclock -s" /SC ONEVENT /EC System /MO "*[System[Provider[@Name='Microsoft-Windows-Kernel-Power'] and (EventID=107 or EventID=507)]]" /F
Right, schtasks can register tasks in Task Scheduler. With this command, the WSL clock drift after waking from sleep can be fixed fairly easily.