Last active
October 30, 2023 07:23
-
-
Save davidfraser/c4c29d03a5730369a615605634fcaee9 to your computer and use it in GitHub Desktop.
Set up WSL2 clock sync
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@echo off | |
rem this is a programmatic reminder of how to set up wsl clock sync | |
rem to prevent clock drift after sleep etc | |
rem see https://stackoverflow.com/a/65086857/120398 and https://github.com/microsoft/WSL/issues/5324 | |
set WSL_UTF8=1 | |
setlocal EnableDelayedExpansion | |
for /F "tokens=* delims=" %%D in ('wsl --list --quiet') DO ( | |
set hwclock_count=0 | |
for /f "tokens=* delims=" %%C in ('wsl -d %%D bash -c "grep -c hwclock /usr/local/sbin/hwclock-sync 2>/dev/null"') DO set hwclock_count=%%C | |
if !hwclock_count! neq 1 ( | |
echo Creating script to retry syncing | |
wsl -d %%D sudo bash -c "{ echo '#!/bin/bash' ; echo 'for try in 1 2 3 4 5; do /usr/sbin/hwclock -s && break || { echo sync failed, retrying >&2 ; sleep 10 ; } done' ; } > /usr/local/sbin/hwclock-sync ; chmod a+x /usr/local/sbin/hwclock-sync" | |
) | |
set hwclock_count=0 | |
for /f "tokens=* delims=" %%C in ('wsl -d %%D bash -c "grep -c hwclock /etc/sudoers.d/hwclock 2>/dev/null"') DO set hwclock_count=%%C | |
if !hwclock_count! neq 1 ( | |
echo Setting up sudo permissions for hwclock on distro %%D - will prompt for password... | |
wsl -d %%D sudo bash -c "echo -e '\x25adm ALL=(ALL) NOPASSWD:/usr/local/sbin/hwclock-sync' > /etc/sudoers.d/hwclock" | |
) else echo hwclock permissions already set up with !hwclock_count! - not changing... | |
echo Testing resetting the clock - shouldn't prompt for password... | |
wsl -d %%D sudo /usr/local/sbin/hwclock-sync | |
set syncname=WSLClockSync%%D | |
echo Creating scheduled task !syncname!... | |
schtasks /create /f /tn "!syncname!" /tr "wsl.exe sudo /usr/local/sbin/hwclock-sync" /sc onevent /ec system /mo "*[System[Provider[@Name='Microsoft-Windows-Kernel-General'] and (EventID=1)]]" | |
echo Scheduling !syncname! to run even when on batteries... | |
powershell -command "& {Set-ScheduledTask !syncname! -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries)}" | |
echo Done! | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment