.NET Console Apps as Scheduled Jobs: Exit Codes, Signals, and Alerts
Contents
A .NET console app run on a schedule tells the scheduler one thing: its exit code. Return 0 only when the work succeeded, return non-zero for every failure, catch exceptions in Main instead of letting them crash the process, turn SIGTERM into a cancellation token, and flush logs before returning. Then add a check outside the process, because no exit code is produced by a run that never started.
This guide covers .NET 8, 9, and 10 console apps run by cron, systemd timers, Windows Task Scheduler, or a Kubernetes CronJob, checked November 16, 2026. It's for apps that start, do one job, and exit. If your schedule lives inside a long-running process instead, see .NET BackgroundService scheduled tasks.
What Each Scheduler Does With the Exit Code#
The scheduler starts the process and reads its exit code, and that's all it knows about your job:
| Scheduler | What non-zero means | Where you see it |
|---|---|---|
| cron | Nothing; cron doesn't act on exit codes | Only in output mailed or logged by your own wrapper |
| systemd timer | The service unit enters the failed state; OnFailure= can react |
systemctl status, journalctl -u |
| Windows Task Scheduler | Recorded as the task's Last Run Result, such as 0x1 |
Task Scheduler library, task history |
| Kubernetes CronJob | The pod fails; the Job retries up to backoffLimit (default 6) |
kubectl get jobs, pod events |
| Docker, CI runners | The container or step is marked failed | Container status, job log |
Cron is the outlier: an app that fails every night under cron produces no signal anywhere unless something else reports it. Kubernetes is the other extreme: a non-zero exit retries the whole run, so a job that partially succeeded will run again, which matters if it isn't idempotent.
Return the Exit Code From Main#
With top-level statements, return sets the exit code. In a classic Program class, declare static async Task<int> Main(string[] args). Either way, the rule is simple: one return 0 on the success path and a non-zero return everywhere else.
Two ways to get this wrong:
async voidor fire-and-forget work. IfMainreturns before the work finishes, the process exits 0 with the job half done. Await everything.Environment.Exit(code)in the middle of the job. It exits immediately:finallyblocks andusingdisposals inMaindon't run, so buffered logs and open transactions are dropped. The Generic Host docs describe the same behavior. SetEnvironment.ExitCodeor return a value instead, and letMainfinish.
Pick a small, documented set of codes. A common split is 0 for success, 1 for failure, and 2 for a run that was cancelled or timed out, so whoever reads the Task Scheduler history or the pod status can tell the difference without the logs.
Don't Let an Exception Escape Main#
An exception that leaves Main is unhandled. .NET writes it to standard error and terminates the process. The exit code is non-zero, but it isn't one you chose: on Linux the runtime aborts, which a shell or kubelet typically reports as 134, and on Windows Task Scheduler shows the CLR's exception code, 0xE0434352. Worse, finally blocks aren't guaranteed to run on that path, so a logger that flushes in a finally may never flush.
Catch at the top, log, and return your own code. Exceptions on other threads, such as a timer callback or an unobserved Task.Run that isn't awaited, still crash the process, so keep the job's work on the awaited path.
Turn SIGTERM Into Cancellation#
Every scheduler except cron has a way to stop a run, and most of them start with SIGTERM:
- Kubernetes sends SIGTERM when a pod is deleted, evicted, or hits
activeDeadlineSeconds, then SIGKILL afterterminationGracePeriodSeconds(default 30). - systemd sends SIGTERM on
systemctl stopor whenRuntimeMaxSec=is reached, then SIGKILL afterTimeoutStopSec=, 90 seconds by default. - Docker sends SIGTERM on
docker stopand SIGKILL 10 seconds later. Use the exec form ofENTRYPOINT(["dotnet", "Export.dll"]) so the signal reaches your process and not a shell. - Windows Task Scheduler ends a task that exceeds "Stop the task if it runs longer than" (three days by default); don't count on cleanup code running when it does.
Since .NET 6, PosixSignalRegistration lets a console app handle SIGTERM directly. Setting context.Cancel = true stops the runtime's default termination, so your code can cancel the work, report the outcome, and return normally. Without a handler, the process ends as soon as the signal arrives.
If you use the Generic Host (Host.CreateApplicationBuilder), its ConsoleLifetime already handles SIGINT, SIGQUIT, and SIGTERM and signals IHostApplicationLifetime.ApplicationStopping, so pass that token into your work instead of registering signals yourself.
Flush Logs Before You Return#
Most loggers buffer. The console provider in Microsoft.Extensions.Logging writes from a background queue, and file or network sinks batch. A process that exits right after logging an error can exit before the error is written, which is how a failed run ends up with an empty log.
- Microsoft.Extensions.Logging: dispose the
ILoggerFactory(or the host or service provider that owns it) beforeMainreturns. Ausingdeclaration at the top ofMaindoes this, as long asMainreturns normally. - Serilog: call
Log.CloseAndFlush()in afinallyblock inMain. - Remote sinks (Application Insights, OpenTelemetry exporters): call their flush or shutdown method; each has its own.
None of this helps if the process is killed with SIGKILL, which is one more reason to finish within the grace period.
A Complete Program#
This console app runs an export, maps every outcome to an exit code, cancels on SIGTERM or Ctrl+C, enforces its own time limit, and flushes logging before exit. It uses the Microsoft.Extensions.Logging.Console package:
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
const int Success = 0;
const int Failed = 1;
const int Cancelled = 2;
using var loggerFactory = LoggerFactory.Create(logging => logging.AddSimpleConsole());
var logger = loggerFactory.CreateLogger("NightlyExport");
// Stop on SIGTERM or Ctrl+C, and give up on our own after 45 minutes.
using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(45));
void RequestStop(PosixSignalContext context)
{
context.Cancel = true; // Keep the process alive so Main can finish and return a code.
cancellation.Cancel();
}
using var onTerm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, RequestStop);
using var onInt = PosixSignalRegistration.Create(PosixSignal.SIGINT, RequestStop);
try
{
var rows = await NightlyExport.RunAsync(cancellation.Token);
logger.LogInformation("Export finished: {Rows} rows", rows);
return Success;
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
{
logger.LogWarning("Export cancelled before it finished");
return Cancelled;
}
catch (Exception error)
{
logger.LogError(error, "Export failed");
return Failed;
}
// Returning (instead of Environment.Exit) disposes loggerFactory, which flushes queued log messages.
static class NightlyExport
{
public static async Task<int> RunAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
return 1_250;
}
}The when filter matters: an OperationCanceledException from an HTTP timeout inside the job isn't a requested stop, so it falls through to the failure branch.
Run It From Each Scheduler#
Publish once (dotnet publish -c Release -o /opt/nightly-export) and point the scheduler at the output.
cron runs with a minimal environment and discards output unless mail is set up, so use absolute paths, set any variables the app needs at the top of the crontab, and log its output (cron environment variables):
# m h dom mon dow command
0 2 * * * cd /opt/nightly-export && ./NightlyExport >> /var/log/nightly-export.log 2>&1systemd gives you the exit status in the unit's state; a Type=oneshot service with a matching timer is the usual shape (systemd timers). Put secrets in an EnvironmentFile= rather than the unit.
Windows Task Scheduler records the code in Last Run Result. Run NightlyExport.exe directly rather than through a .cmd file that might swallow the code; Windows Task Scheduler monitoring covers the settings that skip or stop runs.
Kubernetes CronJob treats a non-zero exit as a failed pod. Set restartPolicy: Never or OnFailure, a backoffLimit that suits the job, concurrencyPolicy: Forbid if runs must not overlap, and a terminationGracePeriodSeconds longer than your cleanup takes. Kubernetes CronJob monitoring covers the rest of the spec.
Get Alerted When a Run Fails or Never Starts#
Exit codes report failures only if a run happens and someone reads the result. Under cron nobody does, and under every scheduler, a run that never started has no exit code at all: a crontab edited away, a timer that wasn't enabled after a reinstall, a CronJob that's suspended or can't schedule its pod, a server that was off. Catching those needs a check that knows the schedule and alerts when the run doesn't arrive.
The CronRadar .NET SDK wraps the job body. Install it and set CRONRADAR_API_KEY where the job runs (crontab line, EnvironmentFile=, task environment, or a Kubernetes Secret):
dotnet add package CronRadarReplace the try block in the program above with a wrapped call:
try
{
var rows = 0;
await CronRadar.CronRadar.WrapAsync("nightly-export", async () =>
{
rows = await NightlyExport.RunAsync(cancellation.Token);
}, schedule: "0 2 * * *");
logger.LogInformation("Export finished: {Rows} rows", rows);
return Success;
}The class has the same name as its namespace, so call it as CronRadar.CronRadar. WrapAsync reports a start, then a completion, or a failure with the exception's message, and re-throws the job's exception unchanged, so the catch blocks and exit codes above still work. Monitoring calls have a five-second timeout and never throw into your code; if CronRadar is unreachable, the job runs as if the SDK weren't there.
The schedule must match the scheduler's, as five-field cron (or a shortcut like @daily). It lets the first report create the monitor and a deleted monitor re-create itself. CronRadar evaluates it in the application's time zone, set in its settings (UTC if unset), so write it in the zone the scheduler uses; a Kubernetes CronJob without timeZone runs in the controller's zone, usually UTC.
What you get:
- Missed: when no start arrives by the expected time plus the grace period, the monitor goes from
warningtocriticaland alerts by email, Slack, webhook, Discord, or PagerDuty, even when the server that should have run the job is off. - Failed: an exception reports
failand alerts immediately. A cancellation from SIGTERM also arrives as a failure, which is accurate: the work didn't finish. - Stuck: a start with no finish, such as a process killed with SIGKILL, is flagged as stuck.
The wrapper reports exceptions, not exit codes. If your job can fail without throwing, for example by returning a non-zero code after logging a validation error, throw inside the delegate instead, or report the failure explicitly with CronRadar.CronRadar.FailJobAsync. For a job you can't change, a shell wrapper around the binary that reports by exit code works too; the getting started guide has one, and the .NET integration guide covers the SDK. Use a separate CronRadar application and key per environment.
Frequently Asked Questions#
How do I return an exit code from a .NET console app?#
Return an int from Main: with top-level statements, return 1; sets the exit code, and in a Program class, declare static int Main or static async Task<int> Main. You can also set Environment.ExitCode and let a void Main return. Avoid Environment.Exit mid-job, because finally blocks and disposals in Main don't run.
What exit code does a .NET app return on an unhandled exception?#
A non-zero code the runtime chooses. On Linux the runtime aborts, which is typically reported as 134; on Windows, Task Scheduler shows 0xE0434352. Because finally blocks aren't guaranteed to run, catch exceptions in Main, log them, and return your own code.
How do I handle SIGTERM in a .NET console app?#
Register a handler with PosixSignalRegistration.Create(PosixSignal.SIGTERM, handler), available since .NET 6. In the handler, set context.Cancel = true and cancel a CancellationTokenSource that your work observes, then return normally from Main. Apps built on the Generic Host get this from ConsoleLifetime through IHostApplicationLifetime.ApplicationStopping.
Why are my console app's last log lines missing?#
The process exited before the logger wrote its buffer. Dispose the ILoggerFactory or host before Main returns, call Log.CloseAndFlush() for Serilog, and avoid Environment.Exit, which skips both. A process killed with SIGKILL after its grace period loses whatever was buffered.
Should a scheduled .NET job be a console app or a BackgroundService?#
A console app run by an external scheduler is simpler when runs are infrequent and independent: the scheduler handles timing, each run gets a fresh process, and the exit code reports the result. A BackgroundService suits frequent work that shares in-memory state, but it must handle its own scheduling, overlap, and scale-out.
Put this guide to work
Connect your .NET job to monitoring
Follow the current integration guide, check the release limitations, and verify a real run and alert delivery.
NuGet installs CronRadar 1.0.15, with heartbeat and lifecycle reporting, execution IDs, outcome values, and CRONRADAR_BASE_URL support. It does not discover jobs automatically.