Asp. Net of C sharing of program instance analysis for automating planned tasks

  • 2020-11-03 22:04:42
  • OfStack

In business complex applications, one or more tasks are sometimes required to be scheduled at a fixed time or at a fixed interval, such as regular backup or synchronization of databases, regular sending of e-mails, etc., which are called scheduled tasks. There are also many ways to implement scheduled tasks, such as using SQLAgent to execute stored procedures, using Windows task schedulers, or using Windows services to complete our scheduled tasks, which are all 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 fees. This article introduces a simple method that can be used directly in an Web application and can be easily implemented without any additional configuration.

Since the ES8en.NET site is run as an Web application and is not thread-bound, it is very easy to create and destroy a scheduled task in the Application_Start and Application_End events. The following is a brief introduction to implementing a scheduled task at the Web site. Our example is to periodically add information to a file. As an example, the current time is periodically written to the file.

The unit of work for 1 scheduled task is called 1 task (Job). The following code describes a common interface for all tasks that can be scheduled for execution by the scheduling engine. Here, each task implements the Execute method for invocation by the scheduling engine:


public interface ISchedulerJob 
{ 
void Execute(); 
} 

As mentioned earlier, our example implements writing to a file as a character date. Here's how to do this:


public class SampleJob : ISchedulerJob 
{ 
public void Execute() 
{ 
// The physical path where the file is saved, CSTest Is the virtual directory name, F:\Inetpub\wwwroot\CSTest Is the physical path  
string p = @"F:\Inetpub\wwwroot\CSTest"; 
// We create it in the root of the virtual directory SchedulerJob Folder, and set permissions to anonymous modifiable,  
//SchedulerJob.txt That's the document that 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"); 
// Whether the tag is a scalar of a 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(); 
} 
// Writes to a file  
StreamWriter x = new StreamWriter(FILE_NAME,true,System.Text.Encoding.Default); 
if(flag) x.Write(" Scheduled task test begins: "); 
x.Write("\r\n"+c); 
x.Close(); 
} 
} 

Next, we set up a configuration object that tells the scheduling engine what tasks to perform and how often.


public class SchedulerConfiguration 
{ 
// The time interval  
private int sleepInterval; 
// The task list  
private ArrayList jobs = new ArrayList(); 
public int SleepInterval { get { return sleepInterval; } } 
public ArrayList Jobs { get { return jobs; } } 
// Schedule the constructor of the configuration class  
public SchedulerConfiguration(int newSleepInterval) 
{ 
sleepInterval = newSleepInterval; 
} 
} 

Below is the scheduling engine, which periodically performs the task of configuring objects


public class Scheduler 
{ 
private SchedulerConfiguration configuration = null; 
public Scheduler(SchedulerConfiguration config) 
{ 
configuration = config; 
} 
public void Start() 
{ 
while(true) 
{ 
// Execute each 1 A task  
foreach(ISchedulerJob job in configuration.Jobs) 
{ 
ThreadStart myThreadDelegate = new ThreadStart(job.Execute); 
Thread myThread = new Thread(myThreadDelegate); 
myThread.Start(); 
Thread.Sleep(configuration.SleepInterval); 
} 
} 
} 
} 

Now that all the preparations are complete, it's time to activate the engine. To allow our task plan to execute, we set up and destroy Applicatio_Start and Application_End in the Global.asax.cs file. First, we set up a thread to schedule the process to run, and the running time 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, the program needs to be destroyed when it exits:


protected void Application_End(Object sender, EventArgs e) 
{ 
if (null != schedulerThread) 
{ 
schedulerThread.Abort(); 
} 
} 

Ok, set up an C# Web application project in ES56en.NET, set up TaskScheduler.cs class, and modify the corresponding ES62en.asax.cs file. In order to see the effect, we set up another form WebForm1.ES66en to refresh 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> in Web An example of performing scheduled tasks in an 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> 

After compiling and running the project, you can see the results, which are as follows:

Scheduled task test begins:
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 this is just a simple example of a scheduled task in an Web application. For multiple tasks, the work needs to be done in different threads, the scheduling of the tasks is also very simple, and in fact requires site congestion and downtime. In addition, there is no error handling and other work, I believe you will write more perfect code.

Click to download the source code: http: / / xiazai ofstack. com / 201401 / yuanma/AutoRun (ofstack. com). zip

Recycle. The timer will recycle and stop when web is not accessed
I don't know if automatic access once in Application_End will work. I've been testing this method for a few days.


void Application_End(object sender, EventArgs e)
{
/// Code that runs when the application is closed 
webSocket.Stop();
Thread.Sleep(15000);
try
{
string url = "http://127.0.0.1/404.aspx?mater=" + DateTime.Now.Ticks;
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
{
Stream resStream = response.GetResponseStream();
}
}
catch (Exception ex)
{
// Abnormal, etc 15s Visit again, 1 Times. 
Thread.Sleep(15000);
string url = "http://127.0.0.1/404.aspx?mater=" + DateTime.Now.Ticks;
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
{
Stream resStream = response.GetResponseStream();
}
Hangjing.AppLog.AppLog.Error("Application_End:" + ex);
}
}


Related articles: