如何使 azure webjob 运行 连续调用 public 静态函数而不自动触发

How to make azure webjob run continuously and call the public static function without automatic trigger

我正在开发一个应该 运行 持续的 azure webjob。我有一个 public 静态函数。我希望这个功能在没有任何队列的情况下自动触发。现在我正在连续使用 while(true) to 运行 。还有其他方法吗?

请在下面找到我的代码

   static void Main()
    {
        var host = new JobHost();
        host.Call(typeof(Functions).GetMethod("ProcessMethod"));
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }

[NoAutomaticTriggerAttribute]
public static void ProcessMethod(TextWriter log)
{
    while (true)
    {
        try
        {
            log.WriteLine("There are {0} pending requests", pendings.Count);
        }
        catch (Exception ex)
        {
            log.WriteLine("Error occurred in processing pending altapay requests. Error : {0}", ex.Message);
        }
        Thread.Sleep(TimeSpan.FromMinutes(3));
    }
}

谢谢

这些步骤会让你得到你想要的:

  1. 将您的方法更改为异步
  2. 等待睡眠
  3. 使用 host.CallAsync() 而不是 host.Call()

我转换了您的代码以反映以下步骤。

static void Main()
{
    var host = new JobHost();
    host.CallAsync(typeof(Functions).GetMethod("ProcessMethod"));
    // The following code ensures that the WebJob will be running continuously
    host.RunAndBlock();
}

[NoAutomaticTriggerAttribute]
public static async Task ProcessMethod(TextWriter log)
{
    while (true)
    {
        try
        {
            log.WriteLine("There are {0} pending requests", pendings.Count);
        }
        catch (Exception ex)
        {
            log.WriteLine("Error occurred in processing pending altapay requests. Error : {0}", ex.Message);
        }
        await Task.Delay(TimeSpan.FromMinutes(3));
    }
}

使用 Microsoft.Azure.WebJobs.Extensions.Timers,请参阅 https://github.com/Azure/azure-webjobs-sdk-extensions/blob/master/src/ExtensionsSample/Samples/TimerSamples.cs 创建使用 TimeSpan 或 Crontab 指令触发方法的触发器。

将 Microsoft.Azure.WebJobs.Extensions.Timers 从 NuGet 添加到您的项目。

public static void ProcessMethod(TextWriter log)

变成

public static void ProcessMethod([TimerTrigger("00:05:00",RunOnStartup = true)] TimerInfo timerInfo, TextWriter log) 

五分钟触发器(使用 TimeSpan 字符串)

您需要确保您的 Program.cs Main 设置配置以使用计时器,如下所示:

static void Main()
    {
        JobHostConfiguration config = new JobHostConfiguration();
        config.UseTimers();

        var host = new JobHost(config);

        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }