[ASP. NET advanced] scheduled execution of tasks (regularly reading and modifying txt file numeric content without refreshing new display results), asp. nettxt

Source: Internet
Author: User

[ASP. NET advanced] scheduled execution of tasks (regularly reading and modifying txt file numeric content without refreshing new display results), asp. nettxt

There are many websites or systems that need to do something regularly on the server, such as clearing invalid data in the database at half past eight every morning. The Demo implementation steps are as follows:

0. first look at the solution

1. Create an ASP. NET project TimedTask and create a Global application file Global. asax.

2. then, start the timer in the Application_Start event. If you need to do one thing every several seconds, that is, the timer is executed in the background and has nothing to do with the client. Even if all the clients are closed, the timer is still executed in the background, the Code is as follows:

Using System; using System. collections. generic; using System. IO; using System. linq; using System. net; using System. threading; using System. timers; using System. web; using System. web. security; using System. web. sessionState; namespace TimedTask {public class Global: System. web. httpApplication {private void AddCount (object sender, ElapsedEventArgs e) {// write the logical code FileControl that needs to be periodically executed here. changeFileNumber ();} prot Ected void Application_Start (object sender, EventArgs e) {System. timers. timer timer = new System. timers. timer (); // AddCount is a method. This method is used for every 1 second. elapsed + = new System. timers. elapsedEventHandler (AddCount); timer. interval = 1000; // set the Interval of the triggering time, which is set to 1 second timer. enabled = true; timer. autoReset = true;} protected void Session_Start (object sender, EventArgs e) {// code to run when a new session starts} protected void Appl Ication_BeginRequest (object sender, EventArgs e) {} protected void Application_AuthenticateRequest (object sender, EventArgs e) {} protected void Application_Error (object sender, EventArgs e) {// code to run when an unprocessed error occurs} protected void Session_End (object sender, EventArgs e) {// code to run when the session ends // note: only in the Web. the Session_End event is triggered only when the sessionstate mode in the config file is set to InProc. If the session mode is set to StateServer or SQLServer, this event will not be thrown} protected void Application_End (object sender, EventArgs e) {// the code that runs when the application is disabled // the following code is critical to solve the problem of automatic collection of IIS application pool // limitations: it can solve the problem of automatic or manual collection of application pool, but it cannot solve the problem of IIS restart or web server restart. Of course, this problem may not occur many times, and if someone accesses your website, the scheduled task is automatically activated. Thread. Sleep (1000); // set your web address here. You can point to any of your aspx pages or even non-existent pages to stimulate Application_Start string url =" http://www.cnblogs.com/yc-755909659/ "; HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest. create (url); HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest. getResponse (); Stream receiveStream = myHttpWebResponse. getResponseStream (); // get the write-back byte stream}/* principle: Global. asax can be an application or session event handler in asp.net. We use Application_Start (Application Start event) and Application_End (Application end event ). * When an application starts, start a timer to regularly execute the AddCount () method. The logic code to be called can be written in this method, which can be a single thread or multiple threads. * When the application ends, for example, the IIS application pool is recycled, so that asp.net can access the current web address. Access An aspx page to reactivate the application. */}}Global. asax

3. Simple implementation of loop events: Read the numbers in the txt file to Increase the number per second

(1) first create the testfile.txt file, which contains the number 1.

(2) read and modify txt files:

Public class FileControl {private const string testFilePath = "~ /Testfile.txt "; public static string GetFileNumber () {// obtain the physical path string filePath = System. web. hosting. hostingEnvironment. mapPath (testFilePath); string text = System. IO. file. readAllText (filePath); return text;} public static string ChangeFileNumber () {string text = GetFileNumber (); string newText = (int. parse (text) + 1) + ""; // increase the number by 1 string filePath = System. web. hosting. hostingEnvironment. mapPath (testFilePath); System. IO. file. writeAllText (filePath, newText, System. text. encoding. UTF8); return text ;}}

4. The test page uses the official control to display file numbers without refreshing

(1) Html code

<!DOCTYPE html>

(2) cs code

namespace TimedTask{    public partial class TestForm : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                TimeStart();            }        }        protected void Timer1_Tick(object sender, EventArgs e)        {            TimeStart();        }        private void TimeStart()        {            lb_Value.Text = "Runtime:" + FileControl.GetFileNumber() + " s";        }    }}

Effect:

 

Source code: TimedTask.zip

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.