Execute scheduled tasks in Web Applications

Source: Internet
Author: User

Complex business applicationsProgram.DatabaseAnd regularly send emails, which are called scheduled tasks. There are also many ways to implement scheduled tasks. You can use SQLAgent to execute stored procedures, or you can useWindowsYou can use the Windows service 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 ASP. NET websites run as web applications and are not restricted by threads, we can easilyAPPLICACreate and destroy a scheduled task in the tion_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

{

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 ";

// 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 ("\ 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

{

// 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.

// Define the thread variable

Public System. Threading. Thread schedulerthread = NULL;

ProTected void application_start (Object sender, eventargs E)

{

// Instantiate the scheduling Configuration

Schedulerconfiguration Config = new schedulerconfiguration (1000*3 );

// Add a task

Config. Jobs. Add (New samplejob ());

Scheduler scheduler = new scheduler (config );

// Create a threadstart delegate

System. Threading. threadstart mythreadstart = new system. Threading. threadstart (Scheduler. Start );

// Instantiate the thread

System. Threading. Thread schedulerthread = new system. Threading. Thread (mythreadstart );

// Start the thread

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">

<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>

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.

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.