msbuild

MSBuild - wait for x seconds


I have a MSBuild script that deploys a web app. It stops the current web app by copying a 'app_offline.htm' file to the server. After this it deletes other files then copies new ones to the server.

I need to add a delay between the copying of 'app_offline.htm' and the delete.

My current script throws errors as the files are still locked when the script tries to delete them.

What is the best way to do this in MSBuild?

My Stop task looks like this...

  <Target Name="Stop">
    <WriteLinesToFile File="$(DeployDirectory)\app_offline.htm" Lines="Offline for maintenance" Overwrite="true" Encoding="Unicode"/>
  </Target>

My Delete task looks like this...

  <Target Name="Clean">
    <ItemGroup>
      <Files Include="$(DeployDirectory)\**\*" Exclude="$(DeployDirectory)\app_offline.htm" />
      <Files Include="$(LogDirectory)\*" />
    </ItemGroup>
    <Delete Files="@(Files)" />
  </Target>

Solution

  • There are multiple options available:

    1. MSBuild Community Tasks has built-in Sleep task. You can use it like this:

      <Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets" />
      <Sleep Milliseconds="300" />
      
    2. MSBuild Extension Pack also contains built-in Thread task which offers Sleep functionality. Example of usage is here.

    3. Of course any kind of cmd-compatible wait can work as well via Exec command:

      • Already mentioned <Exec Command="ping -n 6 127.0.0.1 > nul" />
      • I also had <Exec Command="sleep 5" /> worked for me nicely.
    4. You can define MSBuild inline C# task for that purpose:

      <UsingTask TaskName="Sleep" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
        <ParameterGroup>
          <!-- Delay in milliseconds -->
          <Delay ParameterType="System.Int32" Required="true" />
        </ParameterGroup>
        <Task>
          <Code Type="Fragment" Language="cs">
            <![CDATA[
      System.Threading.Thread.Sleep(this.Delay);
      ]]>
          </Code>
        </Task>
      </UsingTask>
      
      ...
      
      <Sleep Delay="5000"/>