gpt4 book ai didi

azure-webjobs - Azure WebJobs 的正常关闭

转载 作者:行者123 更新时间:2023-12-04 11:06:51 26 4
gpt4 key购买 nike

我计划使用连续的 Azure WebJob 发送电子邮件和推送通知。我了解 WebJobs 会因各种原因不时启动和停止。没关系,但我希望有机会在工作关闭之前“清理”一下。

这样我的 WebJob 可以更新数据库记录的状态或删除每个批次中已经处理过的队列项,这样下次作业运行时就不会发送重复的消息。

试想一下,我尝试将以下代码添加到我的 C# 控制台应用程序中:

Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
{
e.Cancel = true;
program.keepRunning = false;
};

然后我使用keepRunning bool 来控制主while 循环,并在while 循环之外放置一个Console.Writeline("Exited Gracefully")。但这似乎没有帮助。当我告诉作业停止时(使用 Azure 网站的 Webjobs 选项卡中的停止按钮),该作业从列表中消失并显示“无法停止作业:'JobName'”。在 Azure 门户中(在页面底部)。我在 WebJob 的日志中没有看到“优雅退出”文本。所以我去掉了那个代码,因为它没有帮助。

所以,我正在寻找一种好方法,让我的 WebJob 被通知它的秒数已编号并且它需要按顺序处理它的事务。

最佳答案

根据他自己的博客文章,我相信在阿米特最后回答后不久事情就发生了变化:WebJobs Graceful Shutdown

还有 see this video在 6:00+ 标记之后不久进行一些讨论。

来自阿米特的博客:

The way Azure notifies the process it's about to be stopped is by placing (creating) a file at a path that is passed as an environment variable called WEBJOBS_SHUTDOWN_FILE.

Any WebJob that wants to listen on the shutdown notification will actually have to check for the presence of the file (using simple File.Exists function or using a FileSystemWatcher in whatever script language you use), when it shows up the WebJob will need to start cleaning up and break it's current loop where preferably it'll exit properly and Azure will continue the shutdown (of the site) process.



好吧,这听起来好像不是很有趣。虽然 Amit 和其他人已经发布了一些代码来处理这个问题(参见那篇文章),但我发现它仍然比我想要的更笨拙(我更喜欢在代码中处理一次丑陋的细节,然后迅速依赖并忘记)。我希望以下是更好的改进。我真的想要关闭设置的单行通知,这就是我们现在拥有的以下内容。我刚刚测试了这个解决方案,关闭了我的工作,它正确地触发了。

所有工作都放在一个单独的文件/类型中,我将其命名为 WebJobShutdownNotifier。首先,用法:只需在 Main 方法中实例化此类型并传递具有关闭功能的 void 函数(或 lamda)。就是这样!它会触发您的 Shutdown 方法,对此无需多言。我建议 WebJobs 团队将这个或类似的东西直接合并到 JobHost 中。只需提供一个要订阅的事件。

用法示例:

    public static void Main() // your Main method...
{
// nice! a single line to handle the shutdown notification, firing your IsShuttingDown method
var shutdownNotifier = new WebJobShutdownNotifier(IsShuttingDown);

var host1 = new JobHost();
host1.RunAndBlock();
}

public static void IsShuttingDown()
{
Console.WriteLine("Were shutin' down the webjob hatches baby! - {0}", DateTime.UtcNow);
// do something else here if needed...
}

//--- WebJobShutdownNotifier.cs ---

using System;
using System.IO;

namespace Microsoft.Azure.WebJobs.Helper
{
/// <summary>
/// Base info and code adapted and expanded from Amit Apple:
/// http://blog.amitapple.com/post/2014/05/webjobs-graceful-shutdown/.
/// To change the wait on shutdown time from the default of 5 seconds:
/// "create a file called settings.job with the following content: { "stopping_wait_time": 60 }""
/// (Nicholas Petersen)
/// </summary>
public class WebJobShutdownNotifier
{
public bool IsRunning { get; private set; }

public string ShutdownFilePath { get; private set; }

public bool FileEnvironmentVariableExisted { get; private set; }

/// <summary>
/// Set this as an action allowing you to be notified when it fires that
/// shutdown has been triggered (/detected).
/// </summary>
public Action IsShuttingDownNotifier { get; set; }

/// <summary>
/// Constructor.
/// </summary>
/// <param name="isShuttingDownNotifier">
/// Set this as an action allowing you to be notified when it fires that
/// shutdown has been triggered (/detected).
/// </param>
public WebJobShutdownNotifier(Action isShuttingDownNotifier = null, bool exceptionIfNoFileEnvironmentVariable = false)
{
IsRunning = true;
IsShuttingDownNotifier = isShuttingDownNotifier;

// Get the shutdown file path from the environment
ShutdownFilePath = Environment.GetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE");

FileEnvironmentVariableExisted = !string.IsNullOrEmpty(ShutdownFilePath);

if (!FileEnvironmentVariableExisted) {
if (exceptionIfNoFileEnvironmentVariable)
throw new Exception("WEBJOBS_SHUTDOWN_FILE Environment variable returned null or empty.");
}
else {
// Setup a file system watcher on that file's directory to know when the file is created
var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(ShutdownFilePath));
fileSystemWatcher.Created += OnChanged;
fileSystemWatcher.Changed += OnChanged;
fileSystemWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastWrite;
fileSystemWatcher.IncludeSubdirectories = false;
fileSystemWatcher.EnableRaisingEvents = true;
}
}

private void OnChanged(object sender, FileSystemEventArgs e)
{
if (IsRunning) { // this was hitting more than once in the short shut down time, do not want to fire IsShuttingDownNotifier more than once...
if (e.FullPath.IndexOf(Path.GetFileName(ShutdownFilePath), StringComparison.OrdinalIgnoreCase) >= 0) {
// Found the file mark, this WebJob has finished
IsRunning = false;
if (IsShuttingDownNotifier != null)
IsShuttingDownNotifier();
}
}
}

}
}

关于azure-webjobs - Azure WebJobs 的正常关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22429769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com