如何使azure webjob连续运行并在没有自动触发的情况下调用公共静态函数

Muk*_*thi 22 c# azure azure-webjobs

我正在开发一个应该连续运行的天蓝色webjob.我有一个公共静态函数.我希望在没有任何队列的情况下自动触发此功能.现在我正在使用while(true)连续运行.有没有其他方法可以做到这一点?

请在下面找到我的代码

   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));
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

non*_*one 25

这些步骤将帮助您达到您想要的效果:

  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));
    }
}
Run Code Online (Sandbox Code Playgroud)


Roc*_*ave 17

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

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

public static void ProcessMethod(TextWriter log)
Run Code Online (Sandbox Code Playgroud)

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

五分钟触发器(使用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();
    }
Run Code Online (Sandbox Code Playgroud)