Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net web api webapi中的计时器事件_Asp.net Web Api - Fatal编程技术网

Asp.net web api webapi中的计时器事件

Asp.net web api webapi中的计时器事件,asp.net-web-api,Asp.net Web Api,我已经创建了一个计时器事件,尝试在我的web api的后台运行,我发现在本地开发人员机器上调试时它工作正常。但是,当我将它们添加到服务器上的IIS时,计时器不起作用。它在第一个web请求完成后停止(我通过将一些文本写入日志文件来测试它,当web请求完成后,它似乎在几个触发器后停止) 下面是一些示例代码 void refreshTimeStart() { refreshTimer = new System.Timers.Timer(Convert.ToInt32(Confi

我已经创建了一个计时器事件,尝试在我的web api的后台运行,我发现在本地开发人员机器上调试时它工作正常。但是,当我将它们添加到服务器上的IIS时,计时器不起作用。它在第一个web请求完成后停止(我通过将一些文本写入日志文件来测试它,当web请求完成后,它似乎在几个触发器后停止) 下面是一些示例代码

void refreshTimeStart()
    {
        refreshTimer = new System.Timers.Timer(Convert.ToInt32(ConfigurationManager.AppSettings["TIMER_INTERVAL"]));
        refreshTimer.Elapsed += new ElapsedEventHandler(connectionResetEvent);
        refreshTimer.AutoReset = true;
        refreshTimer.Enabled = true;
    }
void connectionResetEvent(object source, ElapsedEventArgs e)
    {
        testIndex = testIndex + 1;
        WriteToFile(testIndex);
               }
static void WriteToFile(int i)
     {
         string text = "This start trigged. ";
         System.IO.File.WriteAllText(@"C:\Projects\abc" + i.ToString() + ".txt", text);
     }

你知道如何做到这一点吗?非常感谢。

这个问题很久以前就被问到了,但这里有一个答案

首先,在Web API中使用计时器可能不是最好的主意。windows服务更合适。尽管如此,您的问题必须来自两个问题:

  • Web API等待请求并仅在第一个请求后初始化。因此,您必须启动计时器启动请求
  • IIS中应用程序池的默认设置有超时。因此,即使您初始化Web API,应用程序池也会在超时时间过后终止。您可以禁用超时