将.NET Core项目部署到Azure WebJob - Azure SDK

前提条件

  1. 已经完成了前四篇文章中的所有步骤。
  2. 安装了Microsoft.Azure.WebJobsMicrosoft.Azure.WebJobs.Extensions包。

创建WebJob

在你的项目中,创建一个新的类:SayHelloWebJob

SayHelloWebJob类中,添加以下代码:

using Microsoft.Azure.WebJobs;
using System;

public class SayHelloWebJob
{
  [Singleton]
  public static void TimerTick([TimerTrigger("0 ")]TimerInfo myTimer)
  {
    Console.WriteLine($"Hello at {DateTime.UtcNow.ToString()}");
  }
}

这个代码定义了一个WebJob,它将在每分钟的开始时运行,并输出当前的UTC时间。

修改Main函数

在你的Program.cs文件中,修改Main函数如下:

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Hosting;

class Program
{
  static void Main()
  {
    var host = new HostBuilder()
    .ConfigureWebJobs(b =>
    {
    b.AddAzureStorageCoreServices();
    b.AddAzureStorage();
    b.AddTimers();
    })
    .Build();

    host.Run();
  }
}

这个代码创建了一个新的Host,并配置了WebJobs以使用Azure Storage和Timers。

使用注意事项

  1. Singleton属性确保了在任何时候只有一个TimerTick方法的实例在运行。这对于避免并发问题非常有用。

  2. TimerTrigger属性定义了一个CRON表达式,它描述了WebJob的运行时间表。

  3. TimerInfo参数提供了关于触发器的信息,例如是否是第一次运行,是否是最后一次运行等。

  4. 你可以在TimerTick方法中添加任何你想要的代码。但是,请注意,这个方法的运行时间应该小于你的CRON表达式的间隔,否则可能会导致并发问题。

  5. HostBuilder是用来创建和配置一个Host的。Host是WebJobs的运行环境,它包含了所有的服务和配置。

  6. AddAzureStorageCoreServicesAddAzureStorage是用来配置WebJobs以使用Azure Storage的。Azure Storage是WebJobs的默认存储后端,它用来存储WebJobs的状态和日志。

  7. AddTimers是用来配置WebJobs以使用Timers的。Timers是WebJobs的一个扩展,它提供了基于时间的触发器。

posted @ 2024-01-19 09:14  初久的私房菜  阅读(6530)  评论(0编辑  收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/