在多个设备上计划作业Schedule jobs on multiple devices

Azure IoT 中心可启用多个构建基块(如设备孪生属性和标记直接方法)。Azure IoT Hub enables a number of building blocks like device twin properties and tags and direct methods. 通常情况下,后端应用允许设备管理员和操作员在计划的时间批量更新 IoT 设备并与之交互。Typically, back-end apps enable device administrators and operators to update and interact with IoT devices in bulk and at a scheduled time. 作业在计划的时间针对一组设备执行设备孪生更新和直接方法。Jobs execute device twin updates and direct methods against a set of devices at a scheduled time. 例如,操作员可使用用于启动和跟踪作业的后端应用在不会中断大楼运作的时间重新启动 43 号大楼第 3 层中的一组设备。For example, an operator would use a back-end app that initiates and tracks a job to reboot a set of devices in building 43 and floor 3 at a time that would not be disruptive to the operations of the building.

Note

本文介绍的功能仅在 IoT 中心的标准层中可用。The features described in this article are available only in the standard tier of IoT Hub. 有关基本和标准/免费 IoT 中心层的详细信息,请参阅选择合适的 IoT 中心层For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier.

在以下情况下请考虑使用作业:需要计划并跟踪一组设备上的以下任何活动的进度:Consider using jobs when you need to schedule and track progress any of the following activities on a set of devices:

  • 更新所需属性Update desired properties
  • 更新标记Update tags
  • 调用直接方法Invoke direct methods

作业生命周期Job lifecycle

作业由解决方案后端启动,并由 IoT 中心维护。Jobs are initiated by the solution back end and maintained by IoT Hub. 可以通过面向服务的 URI (PUT https://<iot hub>/jobs/v2/<jobID>?api-version=2018-06-30) 启动作业,并通过面向服务的 URI (GET https://<iot hub>/jobs/v2/<jobID?api-version=2018-06-30) 查询正在执行的作业的进度。You can initiate a job through a service-facing URI (PUT https://<iot hub>/jobs/v2/<jobID>?api-version=2018-06-30) and query for progress on an executing job through a service-facing URI (GET https://<iot hub>/jobs/v2/<jobID?api-version=2018-06-30). 若要在启动作业后刷新正在运行的作业的状态,请运行作业查询。To refresh the status of running jobs once a job is initiated, run a job query.

Note

启动作业时,属性名称和值只能包含 US-ASCII 可打印字母数字,但下列组中的任一项除外:$ ( ) < > @ , ; : \ " / [ ] ? = { } SP HTWhen you initiate a job, property names and values can only contain US-ASCII printable alphanumeric, except any in the following set: $ ( ) < > @ , ; : \ " / [ ] ? = { } SP HT

用于执行直接方法的作业Jobs to execute direct methods

以下代码片段显示了使用作业在一组设备上执行直接方法的 HTTPS 1.1 请求详细信息:The following snippet shows the HTTPS 1.1 request details for executing a direct method on a set of devices using a job:

PUT /jobs/v2/<jobId>?api-version=2018-06-30

Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8

{
    "jobId": "<jobId>",
    "type": "scheduleDeviceMethod",
    "cloudToDeviceMethod": {
        "methodName": "<methodName>",
        "payload": <payload>,
        "responseTimeoutInSeconds": methodTimeoutInSeconds
    },
    "queryCondition": "<queryOrDevices>", // query condition
    "startTime": <jobStartTime>,          // as an ISO-8601 date string
    "maxExecutionTimeInSeconds": <maxExecutionTimeInSeconds>
}

查询条件也可以位于单个设备 ID 上或位于设备 ID 列表中,如以下示例所示:The query condition can also be on a single device ID or on a list of device IDs as shown in the following examples:

"queryCondition" = "deviceId = 'MyDevice1'"
"queryCondition" = "deviceId IN ['MyDevice1','MyDevice2']"
"queryCondition" = "deviceId IN ['MyDevice1']"

IoT 中心查询语言格外详细地介绍了 IoT 中心查询语言。IoT Hub Query Language covers IoT Hub query language in additional detail.

以下代码片段演示了特定作业的请求和响应,该作业计划在 contoso-hub-1 的所有设备上调用名为 testMethod 的直接方法:The following snippet shows the request and response for a job scheduled to call a direct method named testMethod on all devices on contoso-hub-1:

PUT https://contoso-hub-1.azure-devices.cn/jobs/v2/job01?api-version=2018-06-30 HTTP/1.1
Authorization: SharedAccessSignature sr=contoso-hub-1.azure-devices.cn&sig=68iv------------------------------------v8Hxalg%3D&se=1556849884&skn=iothubowner
Content-Type: application/json; charset=utf-8
Host: contoso-hub-1.azure-devices.cn
Content-Length: 317

{
    "jobId": "job01",
    "type": "scheduleDeviceMethod",
    "cloudToDeviceMethod": {
        "methodName": "testMethod",
        "payload": {},
        "responseTimeoutInSeconds": 30
    },
    "queryCondition": "*", 
    "startTime": "2019-05-04T15:53:00.077Z",
    "maxExecutionTimeInSeconds": 20
}

HTTP/1.1 200 OK
Content-Length: 65
Content-Type: application/json; charset=utf-8
Vary: Origin
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 03 May 2019 01:46:18 GMT

{"jobId":"job01","type":"scheduleDeviceMethod","status":"queued"}

用于更新设备孪生属性的作业Jobs to update device twin properties

以下代码片段显示了使用作业更新设备克隆属性的 HTTPS 1.1 请求详细信息:The following snippet shows the HTTPS 1.1 request details for updating device twin properties using a job:

PUT /jobs/v2/<jobId>?api-version=2018-06-30

Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8

{
    "jobId": "<jobId>",
    "type": "scheduleUpdateTwin",
    "updateTwin": <patch>                 // Valid JSON object
    "queryCondition": "<queryOrDevices>", // query condition
    "startTime": <jobStartTime>,          // as an ISO-8601 date string
    "maxExecutionTimeInSeconds": <maxExecutionTimeInSeconds>
}

Note

updateTwin 属性要求有效的 etag 匹配,例如 etag="*"The updateTwin property requires a valid etag match; for example, etag="*".

以下代码片段演示了特定作业的请求和响应,该作业计划在 contoso-hub-1 上更新 test-device 的设备孪生属性:The following snippet shows the request and response for a job scheduled to update device twin properties for test-device on contoso-hub-1:

PUT https://contoso-hub-1.azure-devices.cn/jobs/v2/job02?api-version=2018-06-30 HTTP/1.1
Authorization: SharedAccessSignature sr=contoso-hub-1.azure-devices.cn&sig=BN0U-------------------------------------RuA%3D&se=1556925787&skn=iothubowner
Content-Type: application/json; charset=utf-8
Host: contoso-hub-1.azure-devices.cn
Content-Length: 339

{
    "jobId": "job02",
    "type": "scheduleUpdateTwin",
    "updateTwin": {
      "properties": {
        "desired": {
          "test1": "value1"
        }
      },
     "etag": "*"
     },
    "queryCondition": "deviceId = 'test-device'",
    "startTime": "2019-05-08T12:19:56.868Z",
    "maxExecutionTimeInSeconds": 20
}

HTTP/1.1 200 OK
Content-Length: 63
Content-Type: application/json; charset=utf-8
Vary: Origin
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 03 May 2019 22:45:13 GMT

{"jobId":"job02","type":"scheduleUpdateTwin","status":"queued"}

查询作业的进度Querying for progress on jobs

以下代码片段显示了用于查询作业的 HTTPS 1.1 请求详细信息:The following snippet shows the HTTPS 1.1 request details for querying for jobs:

GET /jobs/v2/query?api-version=2018-06-30[&jobType=<jobType>][&jobStatus=<jobStatus>][&pageSize=<pageSize>][&continuationToken=<continuationToken>]

Authorization: <config.sharedAccessSignature>
Content-Type: application/json; charset=utf-8

从响应提供 continuationToken。The continuationToken is provided from the response.

可以使用设备孪生、作业和消息路由的 IoT 中心查询语言在每台设备上查询作业执行状态。You can query for the job execution status on each device using the IoT Hub query language for device twins, jobs, and message routing.

作业属性Jobs Properties

以下列表显示了属性和相应说明,在查询作业或作业结果时可使用这些属性。The following list shows the properties and corresponding descriptions, which can be used when querying for jobs or job results.

属性Property 说明Description
jobIdjobId 应用程序提供的作业 ID。Application provided ID for the job.
startTimestartTime 应用程序提供的作业开始时间(ISO-8601)。Application provided start time (ISO-8601) for the job.
endTimeendTime IoT 中心提供的作业完成时的日期(ISO-8601)。IoT Hub provided date (ISO-8601) for when the job completed. 只有在作业达到“完成”状态后才有效。Valid only after the job reaches the 'completed' state.
typetype 作业的类型:Types of jobs:
scheduleUpdateTwin:用于更新一组所需属性或标记的作业。scheduleUpdateTwin: A job used to update a set of desired properties or tags.
scheduleDeviceMethod:用于对一组设备孪生调用设备方法的作业。scheduleDeviceMethod: A job used to invoke a device method on a set of device twins.
statusstatus 作业的当前状态。Current state of the job. 可能的状态值:Possible values for status:
挂起:已计划并等待作业服务选取。pending: Scheduled and waiting to be picked up by the job service.
已计划:计划将来的某个时间。scheduled: Scheduled for a time in the future.
正在运行:当前活动的作业。running: Currently active job.
已取消:作业已取消。canceled: Job has been canceled.
失败:作业失败。failed: Job failed.
完成:作业已完成。completed: Job has completed.
deviceJobStatisticsdeviceJobStatistics 有关作业执行的统计信息。Statistics about the job's execution.
deviceJobStatistics 属性:deviceJobStatistics properties:
deviceJobStatistics.deviceCount:作业中的设备数。deviceJobStatistics.deviceCount: Number of devices in the job.
deviceJobStatistics.failedCount:作业失败的设备数。deviceJobStatistics.failedCount: Number of devices where the job failed.
deviceJobStatistics.succeededCount:作业成功的设备数。deviceJobStatistics.succeededCount: Number of devices where the job succeeded.
deviceJobStatistics.runningCount:当前正在运行作业的设备数。deviceJobStatistics.runningCount: Number of devices that are currently running the job.
deviceJobStatistics.pendingCount:等待运行作业的设备数。deviceJobStatistics.pendingCount: Number of devices that are pending to run the job.

其他参考资料Additional reference material

IoT 中心开发人员指南中的其他参考主题包括:Other reference topics in the IoT Hub developer guide include:

后续步骤Next steps

要尝试本文中介绍的一些概念,请参阅以下 IoT 中心教程:To try out some of the concepts described in this article, see the following IoT Hub tutorial: