In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to realize the program of Asp.Net automatic execution of planned tasks". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to implement the program for Asp.Net to automatically perform scheduled tasks".
Because the ASP.NET site runs as a Web application, it is not subject to thread restrictions, so we can easily set up and destroy a scheduled task in Application_Start and Application_End events. Here's a brief introduction to how to implement scheduled tasks on a Web site. Our example is to add information to the file on a regular basis. As an example, the current time is regularly written to the file.
A unit of work for a scheduled task is called a task (Job). The following code describes a common interface for all tasks that can be scheduled to be executed by the scheduling engine, where each task implements the Execute method that can be called by the scheduling engine:
The copy code is as follows:
Public interface ISchedulerJob
{
Void Execute ()
}
As mentioned earlier, our example is to write a character date to a file, and here is how to do this:
The copy code is as follows:
Public class SampleJob: ISchedulerJob
{
Public void Execute ()
{
/ / the physical path where the file is saved. CSTest is the virtual directory name, and F:\ Inetpub\ wwwroot\ CSTest is the physical path.
String p = @ "F:\ Inetpub\ wwwroot\ CSTest"
/ / We set up a SchedulerJob folder under the root of the virtual directory and set the permissions to anonymous and modifiable
/ / SchedulerJob.txt is the document we wrote.
String FILE_NAME = p + "\\ SchedulerJob\\ SchedulerJob.txt"
/ / get the current server time and convert it to a string
String c = System.DateTime.Now.ToString ("yyyy-mm-dd hh:MM:ss")
/ / whether the tag is a scalar for the newly created 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 to the file
StreamWriter x = new StreamWriter (FILE_NAME,true,System.Text.Encoding.Default)
If (flag) x.Write ("scheduled task test starts:")
X.Write ("\ r\ n" + c)
X.Close ()
}
}
Next, we set up a configuration object that tells the scheduling engine what tasks to perform and the time interval for execution.
The copy code is as follows:
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;}}
/ / the constructor of the scheduling configuration class
Public SchedulerConfiguration (int newSleepInterval)
{
SleepInterval = newSleepInterval
}
}
Here is the scheduling engine, which periodically executes the tasks of the configuration object
The copy code is as follows:
Public class Scheduler
{
Private SchedulerConfiguration configuration = null
Public Scheduler (SchedulerConfiguration config)
{
Configuration = config
}
Public void Start ()
{
While (true)
{
/ / perform every 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 preparatory work has been completed, and here is the work of activating the engine. In order for our task plan to be executed, we set up and destroy in Applicatio_Start and Application_End in the Global.asax.cs file. First, we set up a thread to schedule the process to run, with an interval of 3 seconds.
The copy code is as follows:
Public System.Threading.Thread schedulerThread = null
Protected void Application_Start (Object sender, EventArgs e)
{
SchedulerConfiguration config = new SchedulerConfiguration (1000003)
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, it needs to be destroyed when the program exits:
The copy code is as follows:
Protected void Application_End (Object sender, EventArgs e)
{
If (null! = schedulerThread)
{
SchedulerThread.Abort ()
}
}
All right, create a Web application project for C # in VS.NET, create the TaskScheduler.cs class, and modify the corresponding Global.asax.cs file. To see the effect, let's create another form WebForm1.aspx and refresh it regularly to check the data we recorded:
The copy code is as follows:
An example of performing scheduled tasks in a Web application
Compile and run the project, and you can see the result, as follows:
Schedule the task test to begin:
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 above is only a simple example of performing scheduled tasks in Web applications. For multiple tasks, you need to work in different threads, and the scheduling is also very simple. In fact, it also requires site jams and crashes. In addition, there is no error handling and other work, I believe you will write a more perfect code.
Click to download the source code: http://xiazai.jb51.net/201401/yuanma/AutoRun(jb51.net).zip
Resource recycling. When no one accesses the web, the timer will reclaim and stop.
I don't know if it's useful to visit Application_End automatically. I've been testing this method for a few days.
The copy code is as follows:
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)
{
/ / if there is an exception, wait 15 seconds and visit again.
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)
}
}
At this point, I believe you have a deeper understanding of "how to implement the program of Asp.Net automatic execution of planned tasks". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.