Ping CronMissed from C#
On this page
In .NET one shared HttpClient does the job. This helper sends the start signal, runs your task, and reports success or failure with the end of the exception text, using a ten second timeout and swallowing its own errors.
What should a C# job send?
- A request to
/startbefore the work, so CronMissed can time the run and notice a job that never finishes. - A request to the plain URL when the work succeeded, or to
/failwhen it did not./<exit status>works too: 0 is a success and any other number is a failure. - The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.
What is the helper?
CronMissed.cs
using System.Net.Http;
public static class CronMissed
{
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(10) };
public static async Task PingAsync(string url, string suffix = "", string? body = null)
{
try
{
using var content = body is null ? null : new StringContent(body);
using var response = body is null
? await Http.GetAsync(url + suffix)
: await Http.PostAsync(url + suffix, content);
}
catch (Exception)
{
// a lost ping must never break the job
}
}
public static async Task RunAsync(string url, Func<Task> job)
{
await PingAsync(url, "/start");
try
{
await job();
}
catch (Exception e)
{
var text = e.ToString();
await PingAsync(url, "/fail", text.Length > 100000 ? text[^100000..] : text);
throw;
}
await PingAsync(url);
}
}Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.
Which hosts does this fit?
A console app started by Windows Task Scheduler, a hosted service on a timer, or a container started by Kubernetes. For a long-running worker, call PingAsync after each pass.
Questions and answers
- Creating a client per request can exhaust sockets in a busy process. One shared instance with a timeout is the usual pattern.
- Yes. Call RunAsync around each iteration or PingAsync at the end of each pass; give the check a period that matches the loop.
Why a static HttpClient?
Does this work in a background service?
Create the check these snippets report to
Make a check, copy its ping URL into the snippet, and run the job once.
Start monitoring