Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic code execution in ASP.NET

Tags:

c#

.net

asp.net

My task is to create an ASP.NET application with a piece of code which will automatically run every half an hour. This code must append a record to the file every half an hour. It should not depend on users requests(whether they happen or not).
1) I'm writing my code in Application.Start method of Global.asax file. Am I right?
2) Do I have anything to do with the hosting (IIS) settings (e.g. change permissions to write the file, etc)?

I have already tried just putting the code to write to file into a loop in Application.Start method and then just copied the project directory to the server. However, it didn't work.

like image 981
Dmitry Nagiev Avatar asked Feb 10 '26 15:02

Dmitry Nagiev


1 Answers

You'll need to spawn another thread to have it execute without depending on users. Putting it in a loop in the Application.Start event will basically deadlock the app.

void Application_Start(...)
{
    Thread thread = new Thread(CronThread);
    thread.IsBackground = true;
    thread.Start();
}

private void CronThread()
{
    while(true)
    {
        Thread.Sleep( TimeSpan.FromMinutes( 30 ) );
        // Do something every half hour
    }
}
like image 60
Paul Alexander Avatar answered Feb 12 '26 08:02

Paul Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!