我希望我的web服务每X小时调用一个清理例程,没有任何用户的输入,或者任何对“启动清理服务”的调用。我知道我可以调用一个方法来启动这个服务,但我根本不想要任何用户交互。我想发布这个服务,它会自动启动,并每X小时运行一次清理过程。
有什么想法吗?
发布于 2012-11-07 04:57:40
您可以在Global.asax.cs文件中设置一个每X小时计时一次的计时器,也可以创建一个每X小时计时一次的计划任务,以触发清理服务。
如果项目中没有全局文件,只需向项目中添加一个即可。为此,右键单击项目-> Add -> New Item,然后在弹出的对话框中选择Global Application Class并点击Add。然后,在Application_Start事件中,您可以初始化计时器以执行操作。
public class Global : System.Web.HttpApplication
{
private static System.Threading.Timer timer;
protected void Application_Start(object sender, EventArgs e)
{
var howLongTillTimerFirstGoesInMilliseconds = 1000;
var intervalBetweenTimerEventsInMilliseconds = 2000;
Global.timer = new Timer(
(s) => SomeFunc(),
null, // if you need to provide state to the function specify it here
howLongTillTimerFirstGoesInMilliseconds,
intervalBetweenTimerEventsInMilliseconds
);
}
private void SomeFunc()
{
// reoccurring task code
}
protected void Application_End(object sender, EventArgs e)
{
if(Global.timer != null)
Global.timer.Dispose();
}
}有关全局文件的详细信息,请参阅MSDN
https://stackoverflow.com/questions/13259236
复制相似问题