Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created June 10, 2025 08:28
Show Gist options
  • Save ramonsmits/98b135e9a98f02bd3ebdd2db39006b6f to your computer and use it in GitHub Desktop.
Save ramonsmits/98b135e9a98f02bd3ebdd2db39006b6f to your computer and use it in GitHub Desktop.
NServiceBus - Touch a heartbeat file for external watchdog like monitoring
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