ASP. NET (C #) Periodically executes a piece of code

Source: Internet
Author: User

Global. asax
C # code
Copy codeThe Code is as follows:
<% @ Application Language = "C #" %>
<% @ Import Namespace = "System. IO" %>
<% @ Import Namespace = "System. Threading" %>
<Script runat = "server">
String LogPath;
Thread thread;
Void WriteLog ()
{
While (true)
{
StreamWriter sw = new StreamWriter (LogPath, true, Encoding. UTF8 );
Sw. WriteLine (thread. Name + ":" + DateTime. Now. ToString ());
Sw. Close ();
Thread. CurrentThread. Join (1000*60); // block for 1 minute
}
}
Void Application_Start (object sender, EventArgs e)
{
LogPath = HttpContext. Current. Server. MapPath ("log.txt ");
// Code that runs when the application starts
Thread = new Thread (new ThreadStart (WriteLog ));
Thread. Name = "log writing thread ";
Thread. Start ();
}

Void Application_End (object sender, EventArgs e)
{
// Code that runs when the application is closed

}

Void Application_Error (object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

Void Session_Start (object sender, EventArgs e)
{
// The code that runs when the new session starts

}

Void Session_End (object sender, EventArgs e)
{
// The code that runs when the session ends.
// Note: Only the sessionstate mode in the Web. config file is set
// The Session_End event is triggered only when InProc is used. If the session Mode
// If it is set to StateServer or SQLServer, this event is not triggered.
}
</Script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.