asp.net (C #) Program instance analysis sharing for automatic execution of scheduled tasks

Source: Internet
Author: User
Tags current time datetime sleep thread time interval root directory visual studio

  This article mainly introduces the asp.net (C #) automatic execution Planning task of the program example analysis, the need for friends can refer to the

In a business complex application, it is sometimes required that one or more tasks be scheduled for a certain amount of time or time interval, such as a scheduled backup or synchronization of a database, a timed email, etc., which we call a scheduled task. There are a number of ways to implement a scheduled task, either by using SQLAgent to execute stored procedures, by using Windows Task Scheduler, or by using Windows services to complete our scheduled tasks, which are good solutions. However, for Web applications, these methods are not easy to implement, and host service providers either cannot provide such services directly or require you to pay a lot of extra costs. This article describes an easy way to use directly in a Web application, which is easy to implement without any additional configuration.     Since the ASP.net site is run as a Web application, it is not constrained by threads, so we can easily build and destroy a scheduled task in Application_Start and Application_End events. Here's a quick overview of how to implement a scheduled task on a Web site. Our example is to periodically add information to the file, as an example, where the current time is written to the file at timed intervals.     A working unit of a scheduled task is called a task (job), and the following code describes a generic interface for all tasks to be scheduled by the dispatch engine, where each task implements the Execute method for the dispatch engine to invoke:    Code as follows: public interface ischedulerjob  {  void Execute (); }      As mentioned previously, our example is implemented to write to file as Word Date, the following is the way to accomplish this task:    code is as follows: public class samplejob:ischedulerjob  {  public void Execute ()   {&N Bsp The physical path to the file save, Cstest is the virtual directory name, F:inetpubwwwrootcstest is the physical path   string p = @ "f:inetpubwwwrootcstest"; // We set up the Schedulerjob folder in the root directory of the virtual directory and set permissions to be anonymous modifiable, //schedulerjob.txt is me.Written files   string file_name = p+ "SchedulerJobSchedulerJob.txt"; //Get current server time and convert to string   string c = System.DateTime.Now.ToString ("Yyyy-mm-dd hh:MM:ss"); //Mark is a scalar   BOOL flag = false; //If the file does not exist, Create the new file   if (! File.exists (file_name))   {  flag = true;  StreamWriter sr = File.createtext (file_name);  Sr. Close (); } //To file write content   StreamWriter x = new StreamWriter (File_name,true,system.text.encoding.default) ;  if (flag) X.write ("Scheduled task Test start:");  x.write ("rn" +c);  x.close (); } }      Next, We set up a configuration object that tells the dispatch engine what tasks to perform and what time interval to perform.   Code as follows: public class schedulerconfiguration  { //time interval   private int sleepinterval; //Task List   Private ArrayList jobs = new ArrayList ();    public int Sleepinterval {get {return sleepinterval;}}   Public ArrayList Jobs {get {return jobs;}}    //Dispatching configuration class constructor   public schedulerconfiguration (int newsleepinterval) &nbsP {  sleepinterval = newsleepinterval; } }        The following is the dispatch engine, scheduled to perform the task of the configuration object     &N BSP; code as follows: public class scheduler  {  private schedulerconfiguration configuration = null;    public Sc Heduler (schedulerconfiguration config)   {  configuration = config; }    public void Start () & nbsp {  while (true)   { //Perform each task   foreach (Ischedulerjob job in configuration. Jobs)   {  ThreadStart mythreaddelegate = new ThreadStart (job. Execute);  Thread mythread = new Thread (mythreaddelegate);  Mythread.start ();  Thread.Sleep ( Configuration. Sleepinterval); } } } }        All the preparations have been completed and the following is the work of activating the engine. In order for our mission plan to execute, we build and destroy in the Applicatio_start and Application_End in the Global.asax.cs file, first set up a thread to run the dispatch process, we have a running interval of 3 seconds.       Code as follows: public System.Threading.Thread schedulerthread = null;  protected void Application_Start ( Object sender, EVentargs e)   {  schedulerconfiguration config = new Schedulerconfiguration (1000*3);  config. Jobs.add (New Samplejob ());  Scheduler Scheduler = new Scheduler (config);  Mythreadstart = new System.Threading.ThreadStart (scheduler. Start);  System.Threading.Thread schedulerthread = new System.Threading.Thread (Mythreadstart);  Schedulerthread.start (); }      Finally, you need to destroy the program when it exits:    code as follows: protected void Application_End (Object sender, EventArgs e)   {  if (null!= schedulerthread)   {  schedulerthread.abort (); }&NB Sp }      Well, create a C # Web application project in Vs.net, create TaskScheduler.cs classes, and modify the corresponding Global.asax.cs files. In order to see the effect, we set up a form WebForm1.aspx, timed refresh to check the data we recorded:      code as follows: <%@ Page language= "C #" codebehind= " WebForm1.aspx.cs "autoeventwireup=" false "  inherits=" Cstest.webform1 "%>  <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >  <html>  <HEAD>  <title> Example of executing a scheduled task in a Web application </title>  <meta http-equiv= "Refresh "Content=" >  <meta name= "generator" content= "Microsoft Visual Studio 7.0" >  <meta name= "Code_ LANGUAGE "content=" C # >  <meta name= "vs_defaultClientScript" content= "JavaScript" >  <meta name = "Vs_targetschema" content= "http://schemas.microsoft.com/intellisense/ie5" >  </HEAD>  <body ms_positioning= "GridLayout" >  <form id= "Form1" method= "POST" runat= "server" >  <iframe style= " width:100%;height:100% "src=" Schedulerjob/schedulerjob.txt "></iframe>  </form>  </ body>  </HTML>      The project is compiled and run, you can see the results, the results are as follows:    scheduled task test start:  2003-13-10 11:08:15  2003-13-10 11:08:18  2003-13-10 11:08:21  2003-13-10 11:08:24  2003-13-10 11:08:27  2003-13-10 11:08:30     It is important to note that these are just a few simple examples of executing a scheduled task in a Web application, and for multiple tasks, you need toDifferent threads to work, the planning is also very simple, the actual need for site congestion, when the machine situation. In addition, there is no error processing and other work, I believe you will write more perfect code.   Click to download source code: Http://xiazai.jb51.net/201401/yuanma/AutoRun (jb51.net). zip   Resource Recycling, when no one is accessing the Web, the timer will be recycled and stopped without knowing Application_End when the automatic access is useful, I have been tested for several days before this method can be done. The   code is as follows: void Application_End (object sender, EventArgs e) {///Code websocket.stop () that runs when the application shuts down; Thread.Sleep (15000); try {string url = "http://127.0.0.1/404.aspx?mater=" + DateTime.Now.Ticks; HttpWebRequest HttpWebRequest = (HttpWebRequest) httpwebrequest.create (URL); using (HttpWebResponse response = (HttpWebResponse) httpwebrequest.getresponse ()) {Stream Resstream = response. GetResponseStream (); (Exception ex) {//exception, wait 15s, and then visit again. Thread.Sleep (15000); String url = "http://127.0.0.1/404.aspx?mater=" + DateTime.Now.Ticks; HttpWebRequest HttpWebRequest = (HttpWebRequest) httpwebrequest.create (URL); using (HttpWebResponse response = (HttpWebResponse) httpwebrequest.getresponse ()) {Stream Resstream = response. GetResponseStream (); }   Hangjing.apPLog.AppLog.Error ("Application_End:" + ex);}
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.