Created
June 10, 2025 08:28
-
-
Save ramonsmits/98b135e9a98f02bd3ebdd2db39006b6f to your computer and use it in GitHub Desktop.
NServiceBus - Touch a heartbeat file for external watchdog like monitoring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using NServiceBus.Pipeline; | |
sealed class HeartbeatTouchBehavior : Behavior<IIncomingLogicalMessageContext> | |
{ | |
static readonly string filePath = "C:/watchdog/heartbeat.txt"; | |
static readonly TimeSpan interval = TimeSpan.FromMinutes(1); | |
static DateTime lastTouched = DateTime.MinValue; | |
static readonly object sync = new(); | |
public override Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next) | |
{ | |
var now = DateTime.UtcNow; | |
if ((now - lastTouched) >= interval) | |
{ | |
lock (sync) | |
{ | |
if ((now - lastTouched) >= interval) | |
{ | |
TouchFile(filePath); | |
lastTouched = now; | |
} | |
} | |
} | |
return next(); | |
} | |
static void TouchFile(string path) | |
{ | |
Directory.CreateDirectory(Path.GetDirectoryName(path)!); | |
if (File.Exists(path)) | |
File.SetLastWriteTimeUtc(path, DateTime.UtcNow); | |
else | |
using var _ = File.Create(path); // create empty file | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment