rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

Windows起動時に自動的に時刻合わせする

2024 Jan. 19.
2024 Jan. 13.
2023 Dec. 23.
2023 Dec. 17.

手引き

Windowsで定期的に時刻を同期する | DevelopersIO

時刻合わせバッチファイルを任意のファルダに置く

time_syc.bat

for /f "tokens=3 delims=\ " %%A in ('whoami /groups^|find "Mandatory"') do set LEVEL=%%A
if not "%LEVEL%"=="High" (
  powershell -NoProfile -ExecutionPolicy Unrestricted -Command "Start-Process \"%~f0\" -Verb runas"
  exit
)

sc query W32Time | findstr STATE | findstr RUNNING > NUL
if %ERRORLEVEL% neq 0 (
  net start W32Time
  timeout /T 3 > NUL
)

w32tm /resync
タスクスケジューラ設定xmlファイルを任意のファルダに置く

下部ののパス(PATH_TO_FOLDER)を、時刻合わせバッチファイルへのパスに変更する。

SyncTimeRegularly.xml

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2020-11-25T11:44:20.2557216</Date>
    <Author>yamahiro</Author>
    <URI>\SyncTimeRegularly</URI>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT5M</Interval>
        <Duration>P1D</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2020-11-25T09:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-12-1-322189039-1255377110-817165714-1761623729</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
    <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\PATH_TO_FOLDER\time_syc.bat</Command>
    </Exec>
  </Actions>
</Task>
タスクスケジューラ設定

全般の「タスクの実行に使うユーザーアカウント」に自分のユーザーアカウントを設定する。
トリガーを「スタートアップ時で、トリガー後5分ごとに無期限」とし、「毎日5分ごと」のトリガーを削除する。
以上



以下の方法では、手動では動作したが、タスクスケジューラでスタートアップ時の実行を指定するとうまくいかなかった。

出典 Windowsでログイン時に自動で時刻同期コマンドを実行する #Windows - Qiita

タスクスケジューラで次の内容のバッチファイルを起動時に実行するように設定する

net stop w32time
net start w32time
w32tm /resync