我正在创建一个Azure函数,并希望它在每次运行之间随机延迟运行。我希望从间隔10-20分钟中随机选择每次运行之间的延迟。例如,我想:
这个是可能的吗?谢谢。
发布于 2018-08-16 12:47:07
不要修改functions.json
不要按建议修改functions.json。它会重新启动整个功能应用程序,在我的例子中(使用Node.js)也意味着我在node_modules文件夹中读取/写入数以万计的文件所需的少量但值得注意的钱。
解决方案
您最好的选择是每分钟运行该函数,但大多数情况下立即退出。下面是一个例子。我假设我们希望随机运行函数,但是平均每15分钟运行一次函数。
Node.js
// On average, run the function every N minutes:
const AVERAGE_RUN_EVERY=15;
if (Math.random() > 1 / AVERAGE_RUN_EVERY) {
// Most of the time, we will exit here:
context.done();
} else {
// Your actual code here
}.NET
int AVERAGE_RUN_EVERY = 15;
Random rnd = new Random();
if (rnd.Next(0, AVERAGE_RUN_EVERY) == 0) {
// Your actual code here
}随机运行的额外费用
假设每次执行的最低费用为100 MB,并且应用程序使用的内存为256 MB或更少,则每个月您将收到以下费用:
0.1s * 0.25 GB * 1440分钟/天* 30天* $0.000016/GB/s = 0.02美元
实际上,如果功能应用程序每分钟运行一次,您甚至可能会省钱,因为它不会进入睡眠模式,这意味着该函数将占用更少的启动时间。
发布于 2021-02-17 14:37:20
耐用的功能是要走的路。但是,您可以在ContinueAsNew()中使用IDurableOrchestrationContext方法,而不是使用循环。这将使业务流程重新开始,从而防止您的业务流程历史表使用简单循环的时间过长。
另外,编排器需要是确定性的,所以您不应该在编排器中使用随机数生成器或调用DateTime.Now。
[FunctionName("Orchestrator")]
public static async Task RunOrchestrator([OrchestrationTrigger] IDurableOrchestrationContext context)
{
int delay = await context.CallActivityAsync<int>("Activity", null);
await context.CreateTimer(context.CurrentUtcDateTime.AddMinutes(delay), CancellationToken.None);
context.ContinueAsNew(null);
}
[FunctionName("Activity")]
public static int DoActivity([ActivityTrigger] object input, ILogger log)
{
// Do whatever you want to do at random intervals.
return new Random((int)DateTime.Now.Ticks).Next(1, 60);
}顺便说一句,由于业务流程是如何持久的,在等待您在编排器中创建的计时器时,实际上没有运行任何功能,因此在延迟期间您不会被充电。不过,您仍然要为在客户端和活动功能上花费的等待时间收取费用。
更多信息:
https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-orchestrations
https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-code-constraints
发布于 2018-08-15 04:24:44
使用CreateTimer方法使用持久函数是可能的。
示例:
public static async Task Run(DurableOrchestrationContext ctx)
{
//Do some work here
while (true)
{
// Orchestration will sleep until this time
var nextCheck = ctx.CurrentUtcDateTime.AddSeconds(randomNumber);
await ctx.CreateTimer(nextCheck, CancellationToken.None);
//Call the function again
}
}你可以在这里读到更多关于它的天青耐用功能。
https://stackoverflow.com/questions/51852647
复制相似问题