Running a .NET Console App with Cron
Call `dotnet` by absolute path with your published DLL, set `DOTNET_CLI_HOME` (cron has no `$HOME`), and `cd` into the app directory if it reads `appsettings.json` from the working directory.
The crontab line
0 1 * * * cd /opt/app && DOTNET_CLI_HOME=/opt/app /usr/bin/dotnet MyTask.dll >> /var/log/dotnet-job.log 2>&1
Publish first with dotnet publish -c Release, then run the resulting .dll. Find the runtime with which dotnet (often /usr/bin/dotnet or /usr/local/bin/dotnet).
Set DOTNET_CLI_HOME
Without $HOME the runtime errors with "The HOME environment variable is not set". Export DOTNET_CLI_HOME (and HOME if a library needs it) in the crontab.
appsettings.json
Configuration is loaded relative to the working directory, so cd into the publish folder before launching the DLL.
FAQ
How do I run a .NET app from cron on Linux?
Publish it and call the DLL: 0 1 * * * cd /opt/app && /usr/bin/dotnet MyTask.dll. Set DOTNET_CLI_HOME because cron has no HOME.
Why does dotnet fail in cron with a HOME error?
Cron starts with no $HOME. Set DOTNET_CLI_HOME=/some/writable/dir (and HOME) in the crontab line.
Why can't my .NET cron job read appsettings.json?
It's loaded from the working directory. cd into the published app folder before running the DLL.