Schedule and broadcast jobs (.NET/.NET)

Use Azure IoT Hub to schedule and track jobs that update millions of devices. Use jobs to:

  • Update desired properties
  • Update tags
  • Invoke direct methods

A job wraps one of these actions and tracks the execution against a set of devices that is defined by a device twin query. For example, a back-end app can use a job to invoke a direct method on 10,000 devices that reboots the devices. You specify the set of devices with a device twin query and schedule the job to run at a future time. The job tracks progress as each of the devices receive and execute the reboot direct method.

To learn more about each of these capabilities, see:

Note

The features described in this article are available only in the standard tier of IoT Hub. For more information about the basic and standard IoT Hub tiers, see Choose the right IoT Hub tier.

This tutorial shows you how to:

  • Create a device app that implements a direct method called LockDoor that can be called by the back-end app.

  • Create a back-end app that creates a job to call the LockDoor direct method on multiple devices. Another job sends desired property updates to multiple devices.

At the end of this tutorial, you have two .NET (C#) console apps:

SimulateDeviceMethods that connects to your IoT hub and implements the LockDoor direct method.

ScheduleJob that uses jobs to call the LockDoor direct method and update the device twin desired properties on multiple devices.

To complete this tutorial, you need the following:

  • Visual Studio.
  • An active Azure account. If you don't have an account, you can create a free account in just a couple of minutes.

Create an IoT hub

This section describes how to create an IoT hub using the Azure portal.

  1. Log in to the Azure portal.

  2. Choose +Create a resource, then Search the Marketplace for the IoT Hub.

  3. Select IoT Hub and click the Create button. You see the first screen for creating an IoT hub.

    Create a hub in the Azure portal

    Fill in the fields.

    Subscription: Select the subscription to use for your IoT hub.

    Resource Group: You can create a new resource group or use an existing one. To create a new one, click Create new and fill in the name you want to use. To use an existing resource group, click Use existing and select the resource group from the dropdown list. For more information, see Manage Azure Resource Manager resource groups.

    Region: This is the region in which you want your hub to be located. Select the location closest to you from the dropdown list.

    IoT Hub Name: Put in the name for your IoT Hub. This name must be globally unique. If the name you enter is available, a green check mark appears.

    Important

    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

  4. Click Next: Size and scale to continue creating your IoT hub.

    Set the size and scale for a new IoT hub using the Azure portal

    On this screen, you can take the defaults and just click Review + create at the bottom.

    Pricing and scale tier: You can choose from several tiers depending on how many features you want and how many messages you send through your solution per day. The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the IoT hub and up to 8,000 messages per day. Each Azure subscription can create one IoT Hub in the free tier.

    IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. For example, if you want the IoT hub to support ingress of 700,000 messages, you choose two S1 tier units.

    For details about the other tier options, see Choosing the right IoT Hub tier.

    Advanced / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most IoT hubs only need four partitions.

  5. Click Review + create to review your choices. You see something similar to this screen.

    Review information for creating the new IoT hub

  6. Click Create to create your new IoT hub. Creating the hub takes a few minutes.

Retrieve connection string for IoT hub

After your hub has been created, retrieve the connection string for the hub. This is used to connect devices and applications to your hub.

  1. Click on your hub to see the IoT Hub pane with Settings, and so on. Click Shared access policies.

  2. In Shared access policies, select the iothubowner policy.

  3. Under Shared access keys, copy the Connection string -- primary key to be used later.

    Show how to retrieve the connection string

    For more information, see Access control in the "IoT Hub developer guide."

Register a new device in the IoT hub

In this section, you create a device identity in the identity registry in your IoT hub. A device cannot connect to IoT hub unless it has an entry in the identity registry. For more information, see the "Identity registry" section of the IoT Hub developer guide

  1. In your IoT hub navigation menu, open IoT Devices, then select Add to register a new device in your IoT hub.

    Create device identity in portal

  2. Provide a name for your new device, such as myDeviceId, and select Save. This action creates a new device identity for your IoT hub.

    Add a new device

    Important

    The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  3. After the device is created, open the device from the list in the IoT devices pane. Copy the Connection string---primary key to use later.

    Device connection string

Note

The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. If your application needs to store other device-specific metadata, it should use an application-specific store. For more information, see IoT Hub developer guide.

Create a simulated device app

In this section, you create a .NET console app that responds to a direct method called by the solution back end.

  1. In Visual Studio, add a Visual C# Windows Classic Desktop project to the current solution by using the Console Application project template. Name the project SimulateDeviceMethods.

    New Visual C# Windows Classic device app

  2. In Solution Explorer, right-click the SimulateDeviceMethods project, and then click Manage NuGet Packages....

  3. In the NuGet Package Manager window, select Browse and search for Microsoft.Azure.Devices.Client. Select Install to install the Microsoft.Azure.Devices.Client package, and accept the terms of use. This procedure downloads, installs, and adds a reference to the Azure IoT device SDK NuGet package and its dependencies.

    NuGet Package Manager window Client app

  4. Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices.Client;
    using Microsoft.Azure.Devices.Shared;
    using Newtonsoft.Json;
    
  5. Add the following fields to the Program class. Replace the placeholder value with the device connection string that you noted in the previous section:

    static string DeviceConnectionString = "<yourDeviceConnectionString>";
    static DeviceClient Client = null;
    
  6. Add the following to implement the direct method on the device:

    static Task<MethodResponse> LockDoor(MethodRequest methodRequest, object userContext)
    {
        Console.WriteLine();
        Console.WriteLine("Locking Door!");
        Console.WriteLine("\nReturning response for method {0}", methodRequest.Name);
    
        string result = "'Door was locked.'";
        return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
    }
    
  7. Add the following to implement the device twins listener on the device:

    private static async Task OnDesiredPropertyChanged(TwinCollection desiredProperties, 
      object userContext)
    {
        Console.WriteLine("Desired property change:");
        Console.WriteLine(JsonConvert.SerializeObject(desiredProperties));
    }
    
  8. Finally, add the following code to the Main method to open the connection to your IoT hub and initialize the method listener:

    try
    {
        Console.WriteLine("Connecting to hub");
        Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, 
          TransportType.Mqtt);
    
        Client.SetMethodHandlerAsync("LockDoor", LockDoor, null);
        Client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null);
    
        Console.WriteLine("Waiting for direct method call and device twin update\n Press enter to exit.");
        Console.ReadLine();
    
        Console.WriteLine("Exiting...");
    
        Client.SetMethodHandlerAsync("LockDoor", null, null);
        Client.CloseAsync().Wait();
    }
    catch (Exception ex)
    {
        Console.WriteLine();
        Console.WriteLine("Error in sample: {0}", ex.Message);
    }
    
  9. Save your work and build your solution.

Note

To keep things simple, this tutorial does not implement any retry policy. In production code, you should implement retry policies (such as connection retry), as suggested in the article, Transient Fault Handling.

Schedule jobs for calling a direct method and sending device twin updates

In this section, you create a .NET console app (using C#) that uses jobs to call the LockDoor direct method and send desired property updates to multiple devices.

  1. In Visual Studio, add a Visual C# Windows Classic Desktop project to the current solution by using the Console Application project template. Name the project ScheduleJob.

    New Visual C# Windows Classic Desktop project

  2. In Solution Explorer, right-click the ScheduleJob project, and then click Manage NuGet Packages....

  3. In the NuGet Package Manager window, select Browse, search for Microsoft.Azure.Devices, select Install to install the Microsoft.Azure.Devices package, and accept the terms of use. This step downloads, installs, and adds a reference to the Azure IoT service SDK NuGet package and its dependencies.

    NuGet Package Manager window

  4. Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Shared;
    
  5. Add the following using statement if not already present in the default statements.

    using System.Threading;
    using System.Threading.Tasks;
    
  6. Add the following fields to the Program class. Replace the placeholders with the IoT Hub connection string for the hub that you created in the previous section and the name of your device.

    static JobClient jobClient;
    static string connString = "<yourIotHubConnectionString>";
    static string deviceId = "<yourDeviceId>";
    
  7. Add the following method to the Program class:

    public static async Task MonitorJob(string jobId)
    {
        JobResponse result;
        do
        {
            result = await jobClient.GetJobAsync(jobId);
            Console.WriteLine("Job Status : " + result.Status.ToString());
            Thread.Sleep(2000);
        } while ((result.Status != JobStatus.Completed) && 
          (result.Status != JobStatus.Failed));
    }
    
  8. Add the following method to the Program class:

    public static async Task StartMethodJob(string jobId)
    {
        CloudToDeviceMethod directMethod = 
          new CloudToDeviceMethod("LockDoor", TimeSpan.FromSeconds(5), 
          TimeSpan.FromSeconds(5));
    
        JobResponse result = await jobClient.ScheduleDeviceMethodAsync(jobId,
            $"DeviceId IN ['{deviceId}']",
            directMethod,
            DateTime.UtcNow,
            (long)TimeSpan.FromMinutes(2).TotalSeconds);
    
        Console.WriteLine("Started Method Job");
    }
    
  9. Add another method to the Program class:

    public static async Task StartTwinUpdateJob(string jobId)
    {
        Twin twin = new Twin(deviceId);
        twin.Tags = new TwinCollection();
        twin.Tags["Building"] = "43";
        twin.Tags["Floor"] = "3";
        twin.ETag = "*";
    
        twin.Properties.Desired["LocationUpdate"] = DateTime.UtcNow;
    
        JobResponse createJobResponse = jobClient.ScheduleTwinUpdateAsync(
            jobId,
            $"DeviceId IN ['{deviceId}']", 
            twin, 
            DateTime.UtcNow, 
            (long)TimeSpan.FromMinutes(2).TotalSeconds).Result;
    
        Console.WriteLine("Started Twin Update Job");
    }
    

    Note

    For more information about query syntax, see IoT Hub query language.

  10. Finally, add the following lines to the Main method:

    Console.WriteLine("Press ENTER to start running jobs.");
    Console.ReadLine();
    
    jobClient = JobClient.CreateFromConnectionString(connString);
    
    string methodJobId = Guid.NewGuid().ToString();
    
    StartMethodJob(methodJobId);
    MonitorJob(methodJobId).Wait();
    Console.WriteLine("Press ENTER to run the next job.");
    Console.ReadLine();
    
    string twinUpdateJobId = Guid.NewGuid().ToString();
    
    StartTwinUpdateJob(twinUpdateJobId);
    MonitorJob(twinUpdateJobId).Wait();
    Console.WriteLine("Press ENTER to exit.");
    Console.ReadLine();
    
  11. Save your work and build your solution.

Run the apps

You are now ready to run the apps.

  1. In the Visual Studio Solution Explorer, right-click your solution, and then click Build. Multiple startup projects. Make sure SimulateDeviceMethods is at the top of the list followed by ScheduleJob. Set both their actions to Start and click OK.

  2. Run the projects by clicking Start or go to the Debug menu and click Start Debugging.

  3. You see the output from both device and back-end apps.

    Run the apps to schedule jobs

Next steps

In this tutorial, you used a job to schedule a direct method to a device and the update of the device twin's properties.

To continue getting started with IoT Hub and device management patterns such as remote over the air firmware update, read Tutorial: How to do a firmware update.

To learn about deploying AI to edge devices with Azure IoT Edge, see Getting started with IoT Edge.