Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single instance .NET Core App (or making crontab run only 1 instance of my app)

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) :)

like image 214
SuperJMN Avatar asked Oct 29 '17 21:10

SuperJMN


People also ask

How do I make sure that only one instance of my application runs at a time C#?

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.

What is a single instance application?

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.

What is worker service .NET core?

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.


1 Answers

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\".

like image 187
xneg Avatar answered Sep 28 '22 23:09

xneg