web网站里面,需要每隔1分钟,执行一个任务,并且一直保持这个定时执行状态,可以用如下一个方法:
1,Global.asax里面的 Application_Start ,发生在第一次请求网站的时候,网站关闭(iis关闭网站或者删除网站)
在写这个Application_Start 里面的内容之前,先写个定时器:
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 = value;
}
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;
}
}
}
2,然后,再写Global.asax
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
Time_Task.Instance().ExecuteTask += new System.Timers.ElapsedEventHandler(Global_ExecuteTask);
Time_Task.Instance().Interval = 1000*10;//表示间隔
Time_Task.Instance().Start();
}
void Global_ExecuteTask(object sender, System.Timers.ElapsedEventArgs e)
{
//在这里编写需要定时执行的逻辑代码
}
protected void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
}
protected void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件
}
protected void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
}
}
然后,只要第一次访问网站,就会每隔 10秒(自己定义) 执行定义的任务,可以在要执行的任务里面设置断点,然后调试...