ASP. NET scheduled execution task global. asax

Source: Internet
Author: User

Method 1,
Using System;

Using System. Data;

Using System. Configuration;

Using System. Collections;

Using System. Web;

Using System. Web. Security;

Using System. Web. SessionState;

Using System. Timers;

Using System. Net;

Using System. IO;

Using System. Text;

Using System. Threading;

Namespace qumiao.com

{

Public class Global: System. Web. HttpApplication

{

Protected void Application_Start (object sender, EventArgs e)

{

// Define the timer

System. Timers. Timer myTimer = new System. Timers. Timer (5000 );

MyTimer. Elapsed + = new ElapsedEventHandler (myTimer_Elapsed );

MyTimer. Enabled = true;

MyTimer. AutoReset = true;

}

Void myTimer_Elapsed (object source, ElapsedEventArgs e)

{

Try

{

Log. SaveNote (DateTime. Now. ToString ("yyyy-MM-dd HH: mm: ss") + ": AutoTask is Working! ");

YourTask ();

}

Catch (Exception ee)

{

Log. SaveException (ee );

}

}

Void YourTask ()

{

// Write the task you want to execute here

}

Protected void Application_End (object sender, EventArgs e)

{

Log. SaveNote (DateTime. Now. ToString ("yyyy-MM-dd HH: mm: ss") + ": Application End! ");

// The following code is the key to solve the problem of automatic collection of IIS application pool

Thread. Sleep (1000 );

// Set your web address here, which can point to any of your aspx pages or even non-existent pages to stimulate Application_Start

String url = http://www.shaoqun.com

HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest. Create (url );

HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest. GetResponse ();

Stream receiveStream = myHttpWebResponse. GetResponseStream (); // get the write-back byte Stream

}

}

}

Principle: Global. asax can be an application or session event handler in asp.net. We use Application_Start (Application Start event) and Application_End (Application end event ). When the application starts, start a timer to regularly execute the YourTask () method. In this method, you can write the logic code to be called, which can be single-thread and multi-thread. When the application ends, for example, the application pool of IIS is recycled, so that asp.net can access the current web address. Access An aspx page to reactivate the application. The Log class is a Log recording class. The following is the Log information generated during the test:

========================================================== ======================================

2008-10-30 17: 46: 10: AutoTask is Working!

2008-10-30 17: 46: 15: AutoTask is Working!

2008-10-30 17: 46: 20: AutoTask is Working!

2008-10-30 17: 46: 23: Application End!

2008-10-30 17: 46: 29: AutoTask is Working!

2008-10-30 17: 46: 34: AutoTask is Working!

The log shows that after the application pool of IIS is manually reclaimed, the scheduled task is still being executed, which indicates that our goal has been achieved.

If you comment out the code in Application_End, you will find that the scheduled task stops working after the Application End, as shown below:

========================================================== ======================================

2008-10-30 18: 01: 34: AutoTask is Working!

2008-10-30 18: 01: 39: AutoTask is Working!

2008-10-30 18: 01: 44: AutoTask is Working!

2008-10-30 18: 01: 46: Application End!

Limitations: it can solve the problem of automatic or manual collection of application pools, but it cannot solve the problem of IIS restart or web server restart. Of course, this situation may not occur many times, if someone visits your website, the scheduled task is automatically activated.

Solution 2,

<% @ Application Language = "C #" %>

<% @ Import Namespace = "System. IO" %>

<Script runat = "server">

Void Application_Start (object sender, EventArgs e)

{

// Code that runs when the application starts

System. Timers. Timer myTimer = new System. Timers. Timer (10000 );

MyTimer. Elapsed + = new System. Timers. ElapsedEventHandler (OnTimedEvent );

MyTimer. Interval = 10000;

MyTimer. Enabled = true;

}

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 is set to StateServer

// Or SQLServer, the event is not triggered.

}

Private static void OnTimedEvent (object source, System. Timers. ElapsedEventArgs e)

{

// Execute an action at an interval

// Specify the directory of the log file

String fileLogPath = AppDomain. CurrentDomain. BaseDirectory + "SystemLog ";

String fileLogName = "SoftPrj_CN _" + DateTime. Now. ToLongDateString () + "_log.txt ";

// Define the object of File Information

FileInfo finfo = new FileInfo (fileLogPath + fileLogName );

// Create a file-only stream

Using (FileStream fs = finfo. OpenWrite ())

{

// Create a write data stream based on the file stream created above

StreamWriter strwriter = new StreamWriter (fs );

// Set the start position of the write data stream to the end of the file stream

Strwriter. BaseStream. Seek (0, SeekOrigin. End );

// Write error occurrence time

Strwriter. WriteLine ("occurrence time:" + DateTime. Now. ToString ());

// Write log Content and line feed

// Strwriter. WriteLine ("error content:" + message );

Strwriter. WriteLine ("error content :");

// Write Interval

Strwriter. WriteLine ("---------------------------------------------");

Strwriter. WriteLine ();

// Clear the buffer content and write the buffer content to the base stream

Strwriter. Flush ();

// Close the write data stream

Strwriter. Close ();

Fs. Close ();

}

}

</Script>

Solution 3,

<% @ 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*10); // block 10 seconds

}

}

Void Application_Start (object sender, EventArgs e)

{

LogPath = HttpContext. Current. Server. MapPath ("log.txt"); // the 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 is set to StateServer

// Or SQLServer, the event is not triggered.

}

</Script>

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.