asp.net execution of Scheduled tasks in a Web application (multithreading)

Source: Internet
Author: User
Tags config current time execution implement thread time interval root directory visual studio
asp.net|web| Program | multithreading | execution

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.
Because the ASP.net site is run as a Web application, it is not constrained by threads, so we can easily create and destroy a scheduled task in the 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:

public interface Ischedulerjob
{
void Execute ();
}

As mentioned earlier, our example is to implement a file such as character date, the following is the way to achieve this task: public class Samplejob:ischedulerjob
{
public void Execute ()
{
The physical path to the file save, Cstest to the virtual directory name, F:\Inetpub\wwwroot\CSTest to the physical path
String p = @ "F:\Inetpub\wwwroot\CSTest";
We set up the Schedulerjob folder in the root directory of the virtual directory and set permissions to be anonymous and modifiable,
SchedulerJob.txt is the file we wrote.
string file_name = p+ "\\SchedulerJob\\SchedulerJob.txt";
Gets the current server time and converts it to a string
String c = System.DateTime.Now.ToString ("Yyyy-mm-dd hh:MM:ss");
Mark is a scalar of the new file
BOOL flag = FALSE;
If the file does not exist, create a new file
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 ("Start of scheduled Task test:");
X.write ("\ r \ n" +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. 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;}}

Constructors for scheduling configuration classes
Public schedulerconfiguration (int newsleepinterval)
{
Sleepinterval = Newsleepinterval;
}
}

The following is the dispatch engine, which executes the task public class Scheduler of the configuration object periodically
{
Private schedulerconfiguration configuration = null;

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

public void Start ()
{
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. 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, you need to destroy the program when it exits: protected void Application_End (Object sender, EventArgs e)
{
if (null!= schedulerthread)
{
Schedulerthread.abort ();
}
}

OK, build a C # Web application project in Vs.net, build the TaskScheduler.cs class, and modify the corresponding Global.asax.cs file. In order to see the effect, we set up a form WebForm1.aspx, timed refresh to check the data we recorded
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= "ten" >
<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>


The project is compiled and run, you can see the results, the results are as follows:

To start a scheduled task test:
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 the above is just a simple example of executing a scheduled task in a Web application, and for multiple tasks, it is necessary to work within a different thread, and the scheduling is also simple, and the actual need for site congestion, when the machine. In addition, there is no error processing and other work, I believe you 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.