Schedule Tasks on the Web

Source: Internet
Author: User

In applications with complex services, sometimes one or more tasks are required to be scheduled at a certain time or interval, such as regular backup or database synchronization, scheduled sending of emails is called scheduled tasks. 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. 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: inetpubwwwrootcstest is the physical path.
String P = @ "F: inetpubwwwrootcstest ";
// 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 ";
// Obtain the current server time and convert it to a string
String c = system. datetime. Now. tostring ("yyyy-mm-dd hh: mm: SS ");
// Indicates whether the file is a scalar of the new file.
Bool flag = false;
// If the object does not exist, create the object.
If (! File. exists (file_name ))
{
Flag = true;
Streamwriter sr = file. createtext (file_name );
Sr. Close ();
}
// Write content to the file
Streamwriter x = new streamwriter (file_name, true, system. Text. encoding. Default );
If (FLAG) X. Write ("scheduled task test start :");
X. Write ("" + 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
{
// Time 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 scheduler = new scheduler (config );
System. Threading. threadstart mythreadstart = new system. Threading. threadstart (Scheduler. 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 data we recorded:

<%... @ 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 = "10">
</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>
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
It should be noted that the preceding is a simple example of executing a scheduled task in a web application. For multiple tasks, they need to work in different threads, the plan is also very simple, and the actual site needs to be blocked, when the machine is in the case. In addition, there is no such work as error handling here. I believe everyone will write more perfect code.

Note. In fact, serialization can be used for configuration. It is not good to write the configuration in the file.

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.