如何配置和运行云服务的启动任务How to configure and run startup tasks for a cloud service

在角色启动之前,可以使用启动任务执行操作。You can use startup tasks to perform operations before a role starts. 可能需要执行的操作包括安装组件、注册 COM 组件、设置注册表项或启动长时间运行的进程。Operations that you might want to perform include installing a component, registering COM components, setting registry keys, or starting a long running process.


启动任务不适用于虚拟机,只适用于云服务 Web 角色和辅助角色。Startup tasks are not applicable to Virtual Machines, only to Cloud Service Web and Worker roles.

启动任务的工作方式How startup tasks work

启动任务是在角色开始之前执行的操作,并在 ServiceDefinition.csdef 文件中定义(通过使用 启动 元素内的 任务 元素)。Startup tasks are actions that are taken before your roles begin and are defined in the ServiceDefinition.csdef file by using the Task element within the Startup element. 启动任务通常是批处理文件,但它们也可以是控制台应用程序或启动 PowerShell 脚本的批处理文件。Frequently startup tasks are batch files, but they can also be console applications, or batch files that start PowerShell scripts.

环境变量将信息传递给启动任务,而本地存储可用于从启动任务中传出信息。Environment variables pass information into a startup task, and local storage can be used to pass information out of a startup task. 例如,环境变量可以指定要安装的程序的路径,并可以将文件写入到本地存储,然后角色可以稍后读取这些文件。For example, an environment variable can specify the path to a program you want to install, and files can be written to local storage that can then be read later by your roles.

启动任务可以将信息和错误记录到 TEMP 环境变量指定的目录。Your startup task can log information and errors to the directory specified by the TEMP environment variable. 在云中运行时,在启动任务期间,TEMP 环境变量将解析为 C:\Resources\temp\[guid].[rolename]\RoleTemp 目录。During the startup task, the TEMP environment variable resolves to the C:\Resources\temp\[guid].[rolename]\RoleTemp directory when running on the cloud.

此外,启动任务还可以在重新启动之间执行多次。Startup tasks can also be executed several times between reboots. 例如,每次角色回收时都会运行启动任务,但角色回收可能并非始终包括重新启动。For example, the startup task will be run each time the role recycles, and role recycles may not always include a reboot. 应以这样的方式编写启动任务:使其能够多次运行而不会出现问题。Startup tasks should be written in a way that allows them to run several times without problems.

启动任务必须以为零的 errorlevel (或退出代码)结束,才能完成启动过程。Startup tasks must end with an errorlevel (or exit code) of zero for the startup process to complete. 如果启动任务以非零的 errorlevel 结束,则角色将不会启动。If a startup task ends with a non-zero errorlevel , the role will not start.

角色启动顺序Role startup order

下面列出了 Azure 中的角色启动过程:The following lists the role startup procedure in Azure:

  1. 实例将标记为“ 正在启动 ”并且不接收流量。The instance is marked as Starting and does not receive traffic.

  2. 所有启动任务均根据其 taskType 属性执行。All startup tasks are executed according to their taskType attribute.

    • simple 任务以同步方式执行(一次一个任务)。The simple tasks are executed synchronously, one at a time.

    • backgroundforeground 任务与启动任务并行,以异步方式启动。The background and foreground tasks are started asynchronously, parallel to the startup task.


      在启动过程中的启动任务阶段,IIS 可能未完全配置,因此角色特定的数据可能不可用。IIS may not be fully configured during the startup task stage in the startup process, so role-specific data may not be available. 需要角色特定数据的启动任务应使用 Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.OnStartStartup tasks that require role-specific data should use Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.OnStart.

  3. 将启动角色主机进程并在 IIS 中创建站点。The role host process is started and the site is created in IIS.

  4. 将调用 Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.OnStart 方法。The Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.OnStart method is called.

  5. 实例将标记为“ 就绪 ”,并且流量将路由到实例。The instance is marked as Ready and traffic is routed to the instance.

  6. 将调用 Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.Run 方法。The Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.Run method is called.

启动任务的示例Example of a startup task

启动任务在 ServiceDefinition.csdef 文件的 任务 元素中定义。Startup tasks are defined in the ServiceDefinition.csdef file, in the Task element. commandLine 属性指定启动批处理文件或控制台命令的名称和参数, executionContext 属性指定启动任务的权限级别, taskType 属性指定将如何执行该任务。The commandLine attribute specifies the name and parameters of the startup batch file or console command, the executionContext attribute specifies the privilege level of the startup task, and the taskType attribute specifies how the task will be executed.

在本示例中,将为启动任务创建环境变量 MyVersionNumber ,并将该变量设为值“” 。In this example, an environment variable, MyVersionNumber , is created for the startup task and set to the value " ".

ServiceDefinition.csdefServiceDefinition.csdef :

    <Task commandLine="Startup.cmd" executionContext="limited" taskType="simple" >
            <Variable name="MyVersionNumber" value="" />

在下面的示例中,Startup.cmd 批处理文件会将行“The current version is”写入到由 TEMP 环境变量指定的目录下的 StartupLog.txt 文件中。In the following example, the Startup.cmd batch file writes the line "The current version is" to the StartupLog.txt file in the directory specified by the TEMP environment variable. EXIT /B 0 行确保启动任务以为零的 errorlevel 结束。The EXIT /B 0 line ensures that the startup task ends with an errorlevel of zero.

ECHO The current version is %MyVersionNumber% >> "%TEMP%\StartupLog.txt" 2>&1


在 Visual Studio 中,启动批处理文件的“复制到输出目录”属性应设为“始终复制”,确保将启动批处理文件正确部署到 Azure 上的项目(对于 Web 角色,为 approot\bin;对于辅助角色,为 approot) 。In Visual Studio, the Copy to Output Directory property for your startup batch file should be set to Copy Always to be sure that your startup batch file is properly deployed to your project on Azure ( approot\bin for Web roles, and approot for worker roles).

任务属性的说明Description of task attributes

下面介绍 ServiceDefinition.csdef 文件中的 任务 元素的属性:The following describes the attributes of the Task element in the ServiceDefinition.csdef file:

commandLine - 为启动任务指定命令行:commandLine - Specifies the command line for the startup task:

  • 该命令具有可选的命令行参数,用于开始启动任务。The command, with optional command line parameters, which begins the startup task.
  • 通常它是 .cmd 或 .bat 批处理文件的文件名。Frequently this is the filename of a .cmd or .bat batch file.
  • 该任务相对于部署的 AppRoot\Bin 文件夹。The task is relative to the AppRoot\Bin folder for the deployment. 在确定任务的路径和文件时不扩展环境变量。Environment variables are not expanded in determining the path and file of the task. 如果需要环境扩展,则可以创建用于调用启动任务的小型 .cmd 脚本。If environment expansion is required, you can create a small .cmd script that calls your startup task.
  • 可以是一个启动 PowerShell 脚本的控制台应用程序或批处理文件。Can be a console application or a batch file that starts a PowerShell script.

executionContext - 为启动任务指定权限级别。executionContext - Specifies the privilege level for the startup task. 权限级别可以为 limited 或 elevated:The privilege level can be limited or elevated:

  • limitedlimited
    启动任务以与角色相同的权限运行。The startup task runs with the same privileges as the role. executionContext 元素的 executionContext 属性也是 limited 时,则使用用户权限。When the executionContext attribute for the Runtime element is also limited , then user privileges are used.
  • elevatedelevated
    启动任务以管理员特权运行。The startup task runs with administrator privileges. 这会允许启动任务安装程序、更改 IIS 配置、执行注册表更改和其他管理员级别任务,而不会提高角色本身的权限级别。This allows startup tasks to install programs, make IIS configuration changes, perform registry changes, and other administrator level tasks, without increasing the privilege level of the role itself.


启动任务的权限级别不需要与角色本身相同。The privilege level of a startup task does not need to be the same as the role itself.

taskType - 指定启动任务的执行方式。taskType - Specifies the way a startup task is executed.

  • simplesimple
    任务按照 ServiceDefinition.csdef 文件中指定的顺序一次一个地以同步方式执行。Tasks are executed synchronously, one at a time, in the order specified in the ServiceDefinition.csdef file. 当一个 simple 启动任务以为零的 errorlevel 结束时,将执行下一个 simple 启动任务。When one simple startup task ends with an errorlevel of zero, the next simple startup task is executed. 如果没有更多 simple 启动任务要执行,则将启动角色本身。If there are no more simple startup tasks to execute, then the role itself will be started.


    如果 simple 任务以非零 errorlevel 结束,则将阻止该实例。If the simple task ends with a non-zero errorlevel , the instance will be blocked. 后续 simple 启动任务和角色本身将不会启动。Subsequent simple startup tasks, and the role itself, will not start.

    若要确保批处理文件以为零的 errorlevel 结束,请在批处理文件进程结束时执行命令 EXIT /B 0To ensure that your batch file ends with an errorlevel of zero, execute the command EXIT /B 0 at the end of your batch file process.

  • backgroundbackground
    任务与角色同时启动,并以异步方式执行。Tasks are executed asynchronously, in parallel with the startup of the role.

  • foregroundforeground
    任务与角色同时启动,并以异步方式执行。Tasks are executed asynchronously, in parallel with the startup of the role. foreground 任务与 background 任务之间的主要区别在于 foreground 任务阻止角色回收或关闭,直到任务结束。The key difference between a foreground and a background task is that a foreground task prevents the role from recycling or shutting down until the task has ended. background 任务没有此限制。The background tasks do not have this restriction.

环境变量Environment variables

环境变量是一种将信息传递给启动任务的方法。Environment variables are a way to pass information to a startup task. 例如,可以放置一个 blob 的路径,该 blob 包含要安装的程序或角色将使用的端口号或用于控制启动任务的功能的设置。For example, you can put the path to a blob that contains a program to install, or port numbers that your role will use, or settings to control features of your startup task.

启动任务有两种类型的环境变量;静态环境变量和基于 RoleEnvironment 类的成员的环境变量。There are two kinds of environment variables for startup tasks; static environment variables and environment variables based on members of the RoleEnvironment class. 这两种环境变量都在 ServiceDefinition.csdef 文件的 ServiceDefinition.csdef 节中,并且都使用 变量 元素和 name 属性。Both are in the Environment section of the ServiceDefinition.csdef file, and both use the Variable element and name attribute.

静态环境变量使用 变量 元素的 value 属性。Static environment variables uses the value attribute of the Variable element. 上面的示例创建了环境变量 MyVersionNumber ,该变量具有静态值“ ”。The example above creates the environment variable MyVersionNumber which has a static value of " ". 另一个示例就是创建 StagingOrProduction 环境变量,可以手动将该变量设置为值“ staging ”或“ production ”,以根据 StagingOrProduction 环境变量的值执行不同的启动操作。Another example would be to create a StagingOrProduction environment variable which you can manually set to values of " staging " or " production " to perform different startup actions based on the value of the StagingOrProduction environment variable.

基于 RoleEnvironment 类的成员的环境变量不使用 变量 元素的 value 属性。Environment variables based on members of the RoleEnvironment class do not use the value attribute of the Variable element. 而是使用具有相应 XPath 属性值的 RoleInstanceValue 子元素基于 RoleEnvironment 类的特定成员创建环境变量。Instead, the RoleInstanceValue child element, with the appropriate XPath attribute value, are used to create an environment variable based on a specific member of the RoleEnvironment class. 用于访问各种 RoleEnvironment 值的 XPath 属性值可以在 此处找到。Values for the XPath attribute to access various RoleEnvironment values can be found here.

例如,若要创建这样一个环境变量(当实例在计算模拟器中运行时为“true”,在云中运行时为“false”),请使用以下 变量RoleInstanceValue 元素 :For example, to create an environment variable that is " true " when the instance is running in the compute emulator, and " false " when running in the cloud, use the following Variable and RoleInstanceValue elements:

    <Task commandLine="Startup.cmd" executionContext="limited" taskType="simple">

            <!-- Create the environment variable that informs the startup task whether it is running
                in the Compute Emulator or in the cloud. "%ComputeEmulatorRunning%"=="true" when
                running in the Compute Emulator, "%ComputeEmulatorRunning%"=="false" when running
                in the cloud. -->

            <Variable name="ComputeEmulatorRunning">
                <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />


后续步骤Next steps

了解如何使用云服务执行一些常见的启动任务Learn how to perform some common startup tasks with your Cloud Service.

打包云服务。Package your Cloud Service.