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.

cat related_articles/wsl-clock-sync.yaml

  1. Looking Back on 2024A personal look back at 2024, covering life, building a house, work on AI and information retrieval, and technical projects.
  2. Starting Weekly AI News: automated summaries with clustering and GPTHow a weekly AI newsletter clusters articles with multilingual-e5-small and automatically generates topic titles and summaries with GPT.
  3. Adding type hints to a Python project and getting value from type checkingAdding Python type hints and pyright to a machine learning project, with a low setup cost and immediately useful editor support and static checks.