Keeping a Vagrant Virtual Box's Time Synced
Whilst working on a site I’ve been developing using a Laravel Homestead Vagrant box I discovered that the box’s clock had drifted out of sync with my laptop by about 10 minutes. Normally this wouldn’t be much of an issue for me, but in my case I was trying to authenticate via an API using OAuth and that time difference was causing the authentication to fail. The solution to my authentication issue was to reset Homestead’s clock to the correct time, but obviously over time this would likely go out of sync again.
I’m using Virtual Box for my Vagrant setup which uses an in-guest daemon called VBoxService for time synchronisation. This by default performs a hard resync of the clock once it gets out of sync by more than 20 minutes. Thankfully we can improve this and ensure it is better synchronised with the host system (in my case my MacBook).
To change the threshold we want to edit the startup file for Virtual Box. On my MacBook this file is located at:-
Open this file and look for the following line:-
daemon $binary > /dev/null
Change this to:-
daemon $binary "--timesync-set-start --timesync-set-on-restore 1 --timesync-set-threshold 10000" > /dev/null
This will stop the Vagrant box’s clock from going out of sync with the host by more than 10 seconds (the
10000 threshold is in milliseconds).
Whilst in the startup file it’s also worth lowering the niceness level so that VBoxService doesn’t compete with normal tasks under pressure. To do this, change:-
start-stop-daemon --start --exec $1 -- $2
start-stop-daemon --start --nicelevel "-5" --exec $1 -- $2
Now the Virtual Box won’t go out of sync by more than 10 seconds with the host machine’s clock before attempting to to a hard resync and the API I was authenticating against is happy again.