网络服务背景过程没有人类互动



我希望我的Web服务每x小时调用清洁例程,而没有任何用户的输入或任何"开始清理服务"的呼叫。我知道我可以调用一种启动此服务的方法,但我根本不希望用户交互。我想发布此服务,并自动启动,并每x小时运行我的清理过程。

有什么想法?

您可以在Global.asax.cs文件中设置一个计时器,该计时器每x小时都会停止,或者您还可以创建一个计划的任务,该任务每x小时也会下车以触发清洁服务。

如果您没有项目中的全局文件,则只需在项目中添加一个文件即可。要右键单击项目 -> 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

最新更新