我有一个 Azure Functions 计时器作业,其中从
local.settings.json
获取 CRON 表达式以进行本地开发,并从 Function App 的应用程序设置中获取生产环境。
public static void MyTimerJob([TimerTrigger("%MyTimerCRON%")] TimerInfo Timer, ILogger Log) {
// Function code
}
如果部署环境的应用程序设置中未设置
MyTimerCRON
的默认值,正确的方法是什么?
为了拥有默认值,以防部署时应用程序设置中未设置任何内容,我尝试添加一个新的配置源,该配置源将按照 https://learn.microsoft 中所述的步骤传播到生产环境.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#customizing-configuration-sources:
ConfigurationBuilder
中
IFunctionsConfigurationBuilder
的
ConfigureAppConfiguration
public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
FunctionsHostBuilderContext context = builder.GetContext();
builder.ConfigurationBuilder
.AddJsonFile(Path.Combine(context.ApplicationRootPath, "appsettings.json"), optional: true, reloadOnChange: false)
.AddEnvironmentVariables();
}
.csproj
文件中:<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
appsettings.json
:{
"MyTimerCRON": "* * * * *",
}
但是当运行应用程序时,我会收到以下两条消息:
[2024-11-06T18:33:25.565Z] The Functions scale controller may not scale the following functions correctly because some configuration values were modified in an external startup class.
[2024-11-06T18:33:25.566Z] Function 'MyTimerJob' uses the modified key(s): %MyTimerCRON%
当计时器作业实际执行时,如果我尝试运行
Environment.GetEnvironmentVariable("MyTimerCRON")
返回的值是
null
,这让我相信启动时所做的.AddEnvironmentVariable
并没有达到预期的效果...
在这里,您必须在program.cs中添加依赖项,下面的代码对我有用:
local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"rithcron": "0 */1 * * * *"
}
}
程序.cs:
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var rithcho = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
})
.ConfigureServices((cxt, cho) =>
{
cho.AddApplicationInsightsTelemetryWorkerService();
cho.ConfigureFunctionsApplicationInsights();
var rith = cxt.Configuration["rithcron"];
cho.AddSingleton(new RithTest { RiC = rith });
})
.Build();
rithcho.Run();
public class RithTest
{
public string RiC { get; set; }
}
函数.cs:
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace RithFuncApp
{
public class Function1
{
private readonly ILogger ri_lgr;
public Function1(ILoggerFactory loggerFactory)
{
ri_lgr = loggerFactory.CreateLogger<Function1>();
}
[Function("Function1")]
public void Run([TimerTrigger("%rithcron%")] TimerInfo ritim)
{
ri_lgr.LogInformation($"Hello Rithwik Bojja, C# Timer trigger function executed at: {DateTime.Now}");
}
}
}
输出: