Search code examples
c#timer

call a method only in 30th and 0th second of every minute c#


I have a method which does some calculations.

public void CalculateItems()
{
// Calculate the empty Items
}

Which I need to execute in every 30th second of a minute.

If my service starts at 10:00:15, The method should start working from 10:00:30, 10:01:00, 10:01:30 and goes on.

If my Service starts at 10:00:50, The method should start working from 10:01:00, 10:01:30, 10:02:00 and goes on. I have tried System.Threading.Timer, System.Timers.Timer but in all these, I couldn't achieve my scenario. Please help with your valuable suggestions.

What I have tried is in System.Threading.Timer

var timer = new System.Threading.Timer(
            e => CalculateItems(),
            null,
            TimeSpan.Zero,
            TimeSpan.FromSeconds(30));

But it hits my method every 30th second Not in 30th second of every minute


Solution

  • One simple way to solve it using a timer is to set the interval to a single second, and in the timer's callback method to check if the value of DateTime.Now.Seconds divides by 30:

    void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if(DateTime.Now.Seconds % 30 == 0)
        {
            CalculateItems();
        }
    }