Skip to content

Instantly share code, notes, and snippets.

@noelbundick
Created April 22, 2020 22:51
Show Gist options
  • Save noelbundick/53650f4d69559c21a4f95075d201098a to your computer and use it in GitHub Desktop.
Save noelbundick/53650f4d69559c21a4f95075d201098a to your computer and use it in GitHub Desktop.
WSL2 clock skew hack

Sometimes the system clock in WSL2 can get out of sync with the actual time / hardware clock. Particularly after sleep or hibernate

By adding this to your .bashrc, you can keep your WSL2 instance up to date w/o needing to invoke sudo hwclock -s, scheduling tasks, or otherwise

This is terrible and you probably shouldn't use this.

# WSL2 clock skew hack
__customprompt() {
NOW=$(date +%s)
if (( NOW > WSL_NEXT_CLOCKSYNC )); then
echo "$(date -Iseconds) - hwclock [$WSL_NEXT_CLOCKSYNC : $NOW]" >> ~/.wsltimesync
nohup wsl.exe -u root -c 'hwclock -s' &>/dev/null &
export WSL_NEXT_CLOCKSYNC=$(date --date='+5 minutes' +%s)
fi
}
MIT License
Copyright (c) 2020 Noel Bundick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@MetricMike
Copy link

This is still a terrible workaround that we shouldn't use, BUT the WSL CLI for executing arbitrary commands has changed a bit, so line 6 should be either wsl.exe -u root hwclock -s.

@noelbundick
Copy link
Author

Thanks @MetricMike! Yeah, terrible idea, no one should do this 😆 thanks for the heads up on command changes

I had completely forgotten about this gist. These days I'd probably point people to https://github.com/stuartleeks/wsl-clock as well as jump in on Issues on https://github.com/microsoft/WSL in hopes of a proper fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment