C # scheduled startup of Web Applications

Source: Internet
Author: User

Complex business applicationsProgramIn, sometimes one or more tasks are required to be scheduled at a certain time or within a certain interval, such as regular backup or Database Synchronization, and regular email sending, we call it a scheduled task. There are also many ways to schedule tasks. You can use SQLAgent to execute stored procedures, use Windows Task Scheduling programs, or use Windows Services to schedule tasks, these methods are good solutions. However, for Web applications, the implementation of these methods is not very simple, host service providers or cannot directly provide such services, or you need to pay a lot of extra fees. This article introduces a simple method that is directly used in Web applications. This method can be easily implemented without any additional configuration.

Because the ASP. Net Site runs as a web application and is not restricted by threads, we can easily create and destroy a scheduler task in application_start and application_end events.

The ASP. NET Framework application is created when a request is sent to the server for the first time.Code. When the first request is sent, an httpapplication instance pool is created and application_start event is triggered.
The httpapplication instance processes the request and subsequent requests until the last instance exits and triggers the application_end event.

How to solve the problem that IIS application pool recycle causes timed execution program stop in application_start

The principle is to send a Web request at the end of the application to access the website and start application_start.

Void  Application_end (  Object  Sender, eventargs E)
{
// Code that runs when the application is closed
// Solve application pool recycle Problems
System. Threading. thread. Sleep ( 5000 );
String Strurl = " Website address " ;
System. net. httpwebrequest _ httpwebrequest = (System. net. httpwebrequest) system. net. webrequest. Create (strurl );
System. net. httpwebresponse _ httpwebresponse = (System. net. httpwebresponse) _ httpwebrequest. getresponse ();
System. Io. Stream _ stream = _ Httpwebresponse. getresponsestream (); // Get the write-back byte stream
}

The following describes how to plan tasks on a web site. In our example, information is regularly added to the file. As an example, the current time is regularly written to the file.

The unit of work of a scheduled task is called a job. The following code describes a common interface that can be executed by the scheduling engine for all tasks, each task implements the execute method for the scheduling engine to call:

Public interface ischedulerjob
{
Void execute ();
}

As mentioned above, our example is to write data to a file as a character date. The following describes how to implement this task:

 Public     Class  Samplejob: ischedulerjob
{
Public Void Execute ()
{
// The physical path of the file. cstest is the virtual directory name, and F: \ Inetpub \ wwwroot \ cstest is the physical path.
String P = @" F: \ Inetpub \ wwwroot \ cstest " ;
// Create the schedulerjob folder under the root directory of the virtual directory and set the permission to anonymous,
// Schedulerjob.txt is the file we wrote.
String File_name = P + " \ Schedulerjob \ schedulerjob.txt " ;
// Get the current server time and convert it to a string
String C = System. datetime. Now. tostring ( " Yyyy-mm-dd hh: mm: SS " );
// Indicates whether a new file is a scalar.
Bool Flag = False ;
// If the file does not exist, create a new one.
If ( ! File. exists (file_name ))
{
Flag = True ;
Streamwriter SR = File. createtext (file_name );
Sr. Close ();
}
// Write content to a file
Streamwriter x = New Streamwriter (file_name, True , System. Text. encoding. Default );
If (FLAG) X. Write ( " Scheduled task test starts: " );
X. Write ( " \ R \ n " + C );
X. Close ();
}
}

Next, we will create a configuration object to tell the scheduling engine what task to execute and the interval between the execution.

 Public    Class  Schedulerconfiguration
{
// Interval
Private Int Sleepinterval;
// Task List
Private Arraylist jobs = New Arraylist ();

Public Int Sleepinterval { Get { Return Sleepinterval ;}}
Public Arraylist jobs { Get { Return Jobs ;}}

// Constructor of the scheduling configuration class
Public Schedulerconfiguration ( Int Newsleepinterval)
{
Sleepinterval = Newsleepinterval;
}
}

The following is the scheduling engine, which periodically executes the task of the configuration object.

 Public     Class  Scheduler
{
Private Schedulerconfiguration Configuration = Null ;

Public Scheduler (schedulerconfiguration config)
{
Configuration = Config;
}

Public Void Start ()
{
While ( True )
{
// Execute 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 preparations have been completed. The following describes how to activate the engine. In order to make our task plan run, we. asax. in the CS file applicatio_start and application_end, create and destroy a thread where the scheduling process runs. The running interval here is 3 seconds.

 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 = New Scheduler (config );
System. Threading. threadstart mythreadstart = New System. Threading. threadstart (schedstart. Start );
System. Threading. Thread schedulerthread = New System. Threading. Thread (mythreadstart );
Schedulerthread. Start ();
}

Finally, destroy the program upon exit:

Protected VoidApplication_end (Object sender, eventargs E)
{
If(Null ! =Schedulerthread)
{
Schedulerthread. Abort ();
}
}

All right, create a C # web application project in vs. net, create taskscheduler. CS class, and modify the corresponding global. asax. CS file. In order to see the effect, we create another form webform1.aspx and refresh it regularly to check the data we recorded:

<% @ page Language = "C #" codebehind = "webform1.aspx. CS "autoeventwireup =" false "
inherits =" cstest. webform1 "%>



Web Application example of executing a scheduled task in a program











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.