It is more common to perform a task regularly in a system, such as a typical example of a department reporting data to a parent department on a regular basis, and the following is a simple way to implement a timed execution of a feature in. NET MVC.
1, first modify the Glocal.asax file, at the bottom of the Application_Start method to add:
// define timer 1000 means 1 seconds System.Timers.Timer MyTimer = new System.Timers.Timer (1000 // taskaction.setcontent represents the method to invoke mytimer.elapsed + = new System.Timers.ElapsedEventHandler (taskaction.setcontent); mytimer.enabled = true ;mytimer.autoreset = true ;
The above code runs when the application starts
2. Add the following method to the Glocal.asax file:
voidSession_End (Objectsender, EventArgs e) { //The following code is critical to resolve an issue with automatic collection of IIS application poolsSystem.Threading.Thread.Sleep ( +); //trigger event, write prompt messagetaskaction.setcontent (); //Set your web address here and you can point to any of your ASPX pages or even nonexistent pages to inspire Application_Start//use your own URL stringURL ="http://localhost:3813"; System.Net.HttpWebRequest myhttpwebrequest=(System.Net.HttpWebRequest) System.Net.WebRequest.Create (URL); System.Net.HttpWebResponse Myhttpwebresponse=(System.Net.HttpWebResponse) myhttpwebrequest.getresponse (); System.IO.Stream Receivestream= Myhttpwebresponse.getresponsestream ();//get write-back byte stream//The code that runs at the end of the session. //Note: The Session_End event is raised only if the sessionstate mode in the Web. config file is set to InProc. //if the session mode is set to StateServer//or SQL Server, the event is not raised. }
3, create the above two methods to use the class:
Public Static classtaskaction{Private Static stringContent =""; /// <summary> ///where the output information is stored. /// </summary> Public Static stringContent {Get{returntaskaction.content;} Set{Taskaction.content + ="<div>"+ Value +"</div>"; } } /// <summary> ///method of the Timer delegate task invocation/// </summary> /// <param name= "source" ></param> /// <param name= "E" ></param> Public Static voidSetContent (Objectsource, Elapsedeventargs E) { if(DateTime.Now.ToString ("HH:mm:ss") =="11:35:00") { //Here you write the code that you execute regularlyContent = DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss"+"it's off duty! "); } } /// <summary> ///methods to invoke when applying pool reclamation/// </summary> Public Static voidsetcontent () {Content="END:"+ DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss"); }}
ASP. NET MVC Plan task implementation method (timed to perform a function)