I would like to execute a .NET Core Application on a schedule in Linux using crontab. It's a long running operation and I don't want another instance to be run if a previous execution hasn't finished yet. In other words, I don't want crontab to execute more than one instance of my .NET Core App at a given time.
Is there any way to avoid it? I would prefer not to modify the code of my app. Maybe there is an option for crontab to avoid concurrency. I'm not a Linux expert (yet) :)
The best way of accomplishing this is using a named mutex. Create the mutex using code such as: bool firstInstance; Mutex mutex = new Mutex(false, "Local\\" + someUniqueName, out firstInstance); // If firstInstance is now true, we're the first instance of the application; // otherwise another instance is running.
Single-instanced apps only allow one instance of the app running at a time. WinUI apps are multi-instanced by default. They allow you to launch multiple instances of the same app at one time, which we call multiple instances. However, you may implement single-instancing based on the use case of your app.
17th February 2022. Worker Services were introduced in . NET Core 3.0, and allows for running background services through the use of a hosted service. Another way of running background services is to run hosted services within an ASP.NET Core web application.
For those who want to check instances from code you may use named mutex like this
const string mutexName = @"Global\appName";
var mutex = new Mutex(true, mutexName, out var createdNew);
if (!createdNew)
{
Console.WriteLine(mutexName + " is already running! Exiting the application.");
return;
}
Be sure that your mutex name begins with "Global\"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With