如何让asp.net应用程序定时自动执行代码

如题所述

首先,给你的web应用程序,添加一个“Global.asax”文件,这个类里面默认有一个“Application_Start”,我们就在这个方法里面添加定时程序的逻辑代码。这样,只要有一个人访问了这个web应用,就会启动这个定时程序。为了方便我们对定时程序的管理,我们单独编写一个类,专门用于控制定时程序。这个类中用的核心对象是System.Timers.Timer。下面说一下这个类设计的基本思路:ExecuteTask是一个公共的事件对象,以后调用者可以利用它来添加回调函数。_task是这个类型的唯一静态实例,调用者可以用Instance()方法读取它。_timer就是实现定时运行的对象,Interval是运行的间隔时间。public class Time_Task{ public event System.Timers.ElapsedEventHandler ExecuteTask; private static readonly Time_Task _task = null; private System.Timers.Timer _timer = null; private int _interval = 1000; public int Interval { set { _interval = ; } get { return _interval; } } static Time_Task() { _task = new Time_Task(); } public static Time_Task Instance() { return _task; } public void Start() { if(_timer == null) { _timer = new System.Timers.Timer(_interval); _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); _timer.Enabled = true; _timer.Start(); } } protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if(null != ExecuteTask) { ExecuteTask(sender, e); } } public void Stop() { if(_timer != null) { _timer.Stop(); _timer.Dispose(); _timer = null; } }}有了这个类型,我们可以在Application_Start方法中轻松的实现定时了。
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答