Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WSL2 Clock is out of sync with Windows

WSL2 clock goes out of sync after resuming from sleep/hibernate. illustration showing Windows clock and WSL clock out of sync

A workaround was shared on GitHub sudo hwclock -s to resync clock in WSL, but you have to do this every time you resume from sleep/hibernate.

UPDATE: THIS BUG IS FIXED, just check for updates! See the Clock Sync fix

clock sync fix

like image 984
piouson Avatar asked Dec 01 '20 08:12

piouson


4 Answers

In case anyone finds this via search and doesn't notice that there is actually a solution listed in the question, you can fix WSL clock drift via.

sudo hwclock -s

If you just need to do it occasionally, this is a fine solution. If you need to do it more frequently, consider @piouson's solution

like image 105
Don Alvarez Avatar answered Nov 02 '22 09:11

Don Alvarez


just restart wsl, it works fine for me

wsl --shutdown

then

wsl

in PowerShell

like image 38
fahmiduldul Avatar answered Nov 02 '22 07:11

fahmiduldul


Update

The fix is now in WSL2 Linux kernel 5.10.16.3 and newer! Note you may need to install WSL2 from the Windows Store to get the latest kernel version per this thread with Craig from Microsoft.

Older Answer

sudo hwclock -s gets you kind of there, but for some reason doesn't get the exact time - I often find it's a minute or so in the future!

sudo ntpdate pool.ntp.org should get you the correct time.

But this is all because of a bug in the Linux kernel which should be included in a Windows update at some point...

There are a number of hacks referenced in the the GitHub issue which can work around this, mostly, but not always, in my experience...

like image 24
drkvogel Avatar answered Nov 02 '22 08:11

drkvogel


UPDATE: as mentioned by drkvogel, the Clock Sync fix was released in WSL2 kernel version 5.10.16.3


OBSOLETE

At time of writing, this GitHub Issue was open for the bug.

The workaround I chose for my situation (single distro in WSL2) is to use Windows Task Scheduler to run hwclock in WSL whenever Windows resyncs hardware clock.

Windows: Open PowerShell as Administrator

schtasks /create /tn WSLClockSync /tr "wsl.exe sudo hwclock -s" /sc onevent /ec system /mo "*[System[Provider[@Name='Microsoft-Windows-Kernel-General'] and (EventID=1)]]"
Set-ScheduledTask WSLClockSync -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries)

WSL2: Run sudo visudo and add hwclock to sudoers to skip password prompt

# bottom of my file looks like this
...
...
#includedir /etc/sudoers.d
<username> ALL=(ALL) NOPASSWD:/usr/sbin/hwclock, /usr/bin/apt update, /usr/bin/apt upgrade

Results

illustration showing Windows clock and WSL clock in sync

See image for how to get Event XPath from Windows Event filtering. Use as provided to let task scheduler auto-display scheduled triggers.

illustration showing scheduled task created

like image 20
piouson Avatar answered Nov 02 '22 07:11

piouson