ASP. NET executes scheduled tasks (multithreading) in Web Applications)

Source: Internet
Author: User
Complex business applications Program In, 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 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.CodeDescribes 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
{
VoidExecute ();
}

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 {ReturnSleepinterval ;}}
Public Arraylist jobs {Get {ReturnJobs ;}}

// 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= NewThreadstart (job. Execute );
Thread mythread= NewThread (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 Void Application_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 recorded data.


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 = "10" >
< 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 SRC = "Schedulerjob/schedulerjob.txt" >IFRAME>
Form>
Body>
Html>

Compile and run the project. The result is as follows:

Scheduled task test starts:
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

note that, the above is just a simple example of executing a scheduled task in a web application. For multiple tasks, you need to work in different threads, and the schedule is also very simple, in fact, site congestion is also required. In addition, there is no such work as error handling here. I believe everyone will write more perfect code.

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.