2

I have created a timer event try to running in the background of my web api, I found it works fine when I debugger on local dev machine. However, The timer does not work when I added them to IIS on server. It stops after the first web request finishes( I tested it by writing some text into log files, it seems stopped after a few triggers, once the web request completed) Here is some example code.

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);
     }

Any idea of how to achieve this? Thanks a lot.

1 Answer 1

3

The question was asked a long time ago but here's an answer anyway.

First of all, using a timer in a Web API is probably not the best idea. A windows service would be more appropriate. That being said, your problem must come from two issues:

  1. a Web API awaits a request and only initializes after the first request. So you'll have to initiate a request for your timer to start.
  2. the default settings of application pools in IIS have a timeout. So even if you initialize the Web API, the application pool will terminate after the timeout period has elapsed. You could disable the timeout.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.