c# - 我可以在我的 asp.net mvc 站点触发的特定日期运行一次 Azure 函数吗?

标签 c# asp.net-mvc azure azure-functions

我知道我可以创建一个计划的 Azure 函数来按计划运行。但我想要的是,一旦给定了我传递的特定日期/时间以及一些数据参数,就能够运行 Azure 函数。

例如。我正在我的网站上安排类(class),我想在类(class)结束时向所有学生发送电子邮件。因此,当 10 月 9 日星期一下午 4:00 创建类(class)时,我想发送一条消息以在同一天触发我的 Azure 功能,但要在 1 小时后的下午 5:00 触发。我想向它传递一些信息,比如类 ID 之类的。如果类(class)被取消,我还希望能够删除这个排队的触发器。

这在 Azure 和我的 ASP.Net MVC 站点中可行吗?

最佳答案

实现这一目标的另一种潜在方法是使用 Durable Functions 。我采用了模式 #5 的解决方案,因为您可能会以类取消的形式进行人际交互。

下面是一个未经测试的粗略框架,展示了您的协调器功能的样子。您的电子邮件逻辑将进入一个名为 SendEmail 的函数,该函数利用 ActivityTrigger,您可以使用 these APIs 添加新类并取消它们。

public static async Task Run(DurableOrchestrationContext ctx)
{
    var classInfo = ctx.GetInput<ClassInfo>();
    var targetDateTime = DateTime.Parse(classInfo.ClassEndDateString);
    var maxTimeSpan = new TimeSpan(96, 0, 0);
    using (var timeoutCts = new CancellationTokenSource())
    {
        while(true)
        {
            TimeSpan timeLeft = targetDateTime.Subtract(ctx.CurrentUtcDateTime);
            if(timeLeft <= TimeSpan.Zero) {
                break;
            }

            DateTime checkTime; 
            if(timeLeft > maxTimeSpan) {
                checkTime = ctx.CurrentUtcDateTime.Add(maxTimeSpan);
            } else {
                checkTime = ctx.CurrentUtcDateTime.Add(timeLeft);
            }

            Task durableTimeout = ctx.CreateTimer(checkTime, timeoutCts.Token);

            Task<bool> cancellationEvent = ctx.WaitForExternalEvent<bool>("Cancellation");
            if (cancellationEvent == await Task.WhenAny(cancellationEvent, durableTimeout))
            {
                timeoutCts.Cancel();
                return
            }
        }
        await ctx.CallActivityAsync("SendEmail", classInfo.ClassData);
    }
}

public class ClassInfo {
    public string ClassEndDateString {get; set; }
    public string ClassData {get; set;}
} 

关于c# - 我可以在我的 asp.net mvc 站点触发的特定日期运行一次 Azure 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704892/

相关文章:

c# - 当您发现重复的文件名时,是否有一种简单的方法可以将 (#) 添加到文件名中?

C# 正则表达式模式帮助

javascript - 如何在 Global.asax 中获取 Angular View 的完整 url

sql - 如何将管道从 Azure 数据工厂 V2 移动到另一个(同一资源组)?

c# - 如何使用 .net core c# 将消息从 Deadletter 主题发送到 Main 并完成它

python - Azure Devops 上传图像

c# - Nustache View 引擎 ArrayTypeMismatchException

c# - 为 Type.GetMethod 指定输出参数

c# - OWIN 的 GetExternalLoginInfoAsync 总是返回 null

c# - UserManager.FindByIdAsync(User.Identity.GetUserId()) 是否缓存?