由于ASP.NET站点是作为Web应用程序运行的,它并不受线程的限制,因此我们可以非常方便地在Application_Start和Application_End事件中建立和销毁一个计划任务。下面就简单介绍一下在Web站点实现计划任务的方法。我们的例子是定时往文件里添加信息,作为例子,这里把当前的时间定时地写入文件中。
System.Timers.Timer aTimer = new System.Timers.Timer();//定义定时器
void Application_Start(object sender, EventArgs e)
{
aTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
aTimer.Interval = 3000;//设置间隔时间
aTimer.Start();
}
private void TimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
///在这里添加需要执行的任务
SampleJob sampleJob = new SampleJob();
sampleJob.Execute();
}
void Application_End(object sender, EventArgs e)
{
aTimer.Stop();
}
void Application_Start(object sender, EventArgs e)
{
aTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
aTimer.Interval = 3000;//设置间隔时间
aTimer.Start();
}
private void TimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
///在这里添加需要执行的任务
SampleJob sampleJob = new SampleJob();
sampleJob.Execute();
}
void Application_End(object sender, EventArgs e)
{
aTimer.Stop();
}