我正在开发一个应该连续运行的天蓝色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));
}
}
由于
答案 0 :(得分:24)
这些步骤可以帮助您实现目标:
我转换了您的代码以反映以下步骤。
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));
}
}
答案 1 :(得分:16)
使用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)
变为
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();
}