ASP.net Program task management program implementation, multithreading task loading _ Practical skills

Source: Internet
Author: User
Tags error handling month name time interval
asp.net implementation can put the method of planning tasks in global, using a unified task management class to manage the implementation of various tasks, to achieve parallel!
Here is a method I wrote, I hope to play a role! All of you study together:

The first step defines an interface that is used to standardize the actions that a task must implement, which has only one method (for simplicity):

Copy Code code as follows:

<summary>
Work unit interface, define the work that a scheduled task must complete
</summary>
public interface Ischeduledtask
{
<summary>
Task execution
</summary>
void Execute ();
}


The second step is to define a class that manages the execution and shutdown of scheduled tasks:

Copy Code code as follows:

<summary>
The basic object used to perform the scheduled task
</summary>
public class Scheduledtask
{
private static readonly Scheduledtask _scheduledtask = null;

Private Timer Updatetimer = null;

<summary>
Interval time, in milliseconds
</summary>
private int interval = 10 * 1000;
<summary>
Interval time, in milliseconds
</summary>
public int Interval
{
get {return this.interval;}
set {this.interval = value;}
}
<summary>
Whether the task completes the flag
</summary>
private int _isrunning;

<summary>
Static constructor to guarantee the uniqueness of the instance
</summary>
Static Scheduledtask ()
{
_scheduledtask = new Scheduledtask ();
}
<summary>
Task queues
</summary>
Private ArrayList tasks = new ArrayList ();
<summary>
Task queues
</summary>
Public ArrayList Tasks {get {return tasks}}

<summary>
Return Task Instance
</summary>
<returns></returns>
public static Scheduledtask Instance ()
{
return _scheduledtask;
}

<summary>
Perform tasks
</summary>
public void Start ()
{
if (Updatetimer = null)
{
Updatetimer = new Timer (new TimerCallback (updatetimercallback), null, interval, interval);
}
}

<summary>
Task processing
</summary>
<param name= "Sender" ></param>
private void Updatetimercallback (object sender)
{
if (Interlocked.exchange (ref _isrunning, 1) = = 0)
{
Try
{
Perform multiple tasks
foreach (ischeduledtask task in Tasks)
{
ThreadStart mythreaddelegate = new ThreadStart (task. Execute);
Thread mythread = new Thread (mythreaddelegate);
Mythread.start ();
}
}
catch (Exception ex)
{
Error handling
Createlog (ex. message, true);
}
Finally
{
Interlocked.exchange (ref _isrunning, 0);
}
}
}

<summary>
Cancel a task
</summary>
public void Stop ()
{
if (Updatetimer!= null)
{
Updatetimer.dispose ();
Updatetimer = null;
}
}

<summary>
Logging to a text file
</summary>
<param name= "Message" ></param>
<param name= "IsError" ></param>
public static void Createlog (String message, bool IsError)
{
DateTime dt = DateTime.Now;
int y = dt. year;//the current year
int m = dt. month;//the current month

string root = Httpruntime.appdomainapppath;

Root = = "Scheduledtasklogs";

if (! File.exists (Root)) directory.createdirectory (root);

String dir_y = root + "\" + y.tostring ();
String dir_m = dir_y + "\" + m.tostring ();
String err = IsError? "_taskerror": "_task";
String Dirok = dir_m + "\" + dt. Year + dt. Month + dt. Day + err + ". txt";

Create a new directory with the current year as the name
if (! File.exists (dir_y)) directory.createdirectory (dir_y);

Create a new directory with the current month name
if (! File.exists (dir_m)) directory.createdirectory (dir_m);

String err1 = IsError? "Error": "";

if (file.exists (Dirok))
{
StreamWriter sr = new StreamWriter (Dirok, True, Encoding.default);
Lock (SR)
{
Sr. WriteLine ();
Sr. WriteLine ("--------------scheduled task + err1 +" Log----------------------------------------------------------------------- ");
Sr. WriteLine (err1 + "time:" + DateTime.Now.ToString ());
Sr. WriteLine ("Details:" + message);
Sr. WriteLine ("--------------------------------------------------------------------------------------------");
}
Sr. Close ();
Sr. Dispose ();
}
Else
{
StreamWriter sr = new StreamWriter (Dirok, False, Encoding.default);
Lock (SR)
{
Sr. WriteLine ();
Sr. WriteLine ("--------------scheduled task + err1 +" Log----------------------------------------------------------------------- ");
Sr. WriteLine (err1 + "time:" + DateTime.Now.ToString ());
Sr. WriteLine ("Details:" + message);
Sr. WriteLine ("--------------------------------------------------------------------------------------------");
}
Sr. Close ();
Sr. Dispose ();
}
}
}

The third step is to define the action processing class to be done, inherit the interface defined in the first step, and the following example is a timed mail sending program that performs a message delivery in a specified time period:
Copy Code code as follows:

<summary>
Scheduled tasks-sending messages regularly
</summary>
public class Task_mailsend:ischeduledtask
{
public void Execute ()
{
string NW = DateTime.Now.ToString ("HH");

int hh = 0;
if (! Int32.TryParse (NW, out hh)) {return;}

Send mail at 11-13 o ' Day
if (hh < | | hh > 17)
{
Scheduledtask.createlog ("Not Sent Time", true);
Return
}

DataTable dt = Getordereduser ();
int num = dt. Rows.Count;
if (num = 0)
{
Scheduledtask.createlog ("No user subscriptions currently", true);
Return
}
/*

Mail Send program ...
*/
}

Well, after three steps, the rest of the work will be given to global!

Copy Code code as follows:

<script runat= "Server" ><!--

void Application_Start (object sender, EventArgs e)
{
Code that runs when the application starts
Wildren.common is my namespace here.
WildRen.Common.ScheduledTask.Instance (). Interval = 12 * 60 * 60000;//Set Scheduled task execution time interval
WildRen.Common.ScheduledTask.Instance (). Tasks.add (New Task_mailsend ());//Add the action to be performed to the scheduled Task manager
WildRen.Common.ScheduledTask.Instance (). Start ()//Launch task
}

void Application_End (object sender, EventArgs e)
{
Code that runs when the application shuts down
WildRen.Common.ScheduledTask.Instance (). Stop ();

}

--></script>

If you are using AJAX to connect this management class to simulate client timer events, it is OK! Of course, the method is not unique, this procedure may have some deficiencies, you are welcome to correct the point!
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.