0

I have a windows service application. I want this windows service to run a method after every x minutes. I also want when the existing method is running, it should not allow the timer method to execute. I have,

    private static readonly ILogger Logger = GetLogger();
    private Timer _timer;
    protected override void OnStart(string[] args)
    {
        Logger.Log("Starting Timer");
        StartTimer();
    }

    protected override void OnStop()
    {
        Logger.Log("Stoping Timer");
        StopTimer();
    }

    private void Timer_Elapsed(object state)
    {
        Logger.Log("Timer Elapsed");
        DoWork();
        RestartTimer();
    }

    private static void DoWork()
    {
        try
        {
            // Doing my work there
        }
        catch (Exception ex)
        {
            Logger.Log(ex);
        }
    }

    private void StartTimer()
    {
        Logger.Log("Running first time manually");
        ThreadPool.QueueUserWorkItem((_) => DoWork());
        var frequency = GetTimerFrequency();
        _timer = new Timer(Timer_Elapsed, null, frequency, Timeout.Infinite);
    }

    private void RestartTimer()
    {
        var frequency = GetTimerFrequency();
        _timer.Change(frequency, Timeout.Infinite);
    }

    private void StopTimer()
    {
        _timer.Change(Timeout.Infinite, Timeout.Infinite);
        _timer.Dispose();
        _timer = null;
    }

I dunno why but some-times when the method DoWork is running, Timer_Elapsed is executing. I want until one DoWork finished, no more DoWork is allowed to execute.

user960567
  • 28,664
  • 58
  • 165
  • 292
  • Is this happening only for that first one you run on the thread pool, or does it happen for ones after that? – juharr Mar 11 '15 at 13:13
  • I think it will only happen first one. – user960567 Mar 11 '15 at 13:14
  • Is there a reason you couldn't run the first one synchronously then start up the timer? – juharr Mar 11 '15 at 13:15
  • 2
    Check [How to let Timer skip tick if the previous thread is still busy](http://stackoverflow.com/questions/3424907/how-to-let-timer-skip-tick-if-the-previous-thread-is-still-busy) – Kurubaran Mar 11 '15 at 13:15

1 Answers1

0

Possible Duplicate of this post. You have to check the status of the app whether its already running or not.

Here

Community
  • 1
  • 1
Gaurav Sharma
  • 558
  • 3
  • 10