我正在使用WebJobs SDK v3.0.5,使用非常简单的.NET Core 2.2控制台项目,如下所示:
TimerHost.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<LangVersion>7.1</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.5" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Program.cs中
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace TimerHost
{
public class Program
{
public static async Task Main()
{
var builder = new HostBuilder();
var host = builder
.UseEnvironment("Development")
.ConfigureServices((context, services) =>
{
services.AddSingleton(context.Configuration);
})
.ConfigureWebJobs(webJobsBuilder =>
{
webJobsBuilder
.AddAzureStorageCoreServices()
.AddTimers();
})
.ConfigureLogging((context, b) =>
{
b.SetMinimumLevel(LogLevel.Debug);
b.AddConsole();
})
.UseConsoleLifetime()
.Build();
await host.RunAsync();
}
}
public static class Function
{
public static void Run([TimerTrigger("*/10 * * * * *")] TimerInfo timer, ILogger logger)
{
logger.LogInformation($"Running job for timer. Next 3 runs are: {timer.FormatNextOccurrences(3)}");
}
}
}
appsettings.json
{
}
触发器运行正常。但是,根据最新的文档(https://docs.microsoft.com/en-us/azure/app-service/webjobs-sdk-how-to#multiple-instances),计时器应隐式运行为单例,这意味着它应该使用Azure存储帐户进行分布式锁定支持。
在本地使用Azure Functions时,我希望提供如下设置:
{
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
否则我实际上无法运行一个函数,我得到一个错误,说这个设置是必需的,但是在Console主机示例中,我根本没有得到任何错误。
有人可以解释为什么控制台主机不需要使用默认存储帐户吗?在这种情况下,计时器如何维持单例行为?
我花了一些时间从我的应用程序调试WebJobs SDK源代码,并找到更多关于幕后发生的事情的信息: