Alex27
Alex27

Reputation: 89

c# timer synchronize with system clock

I have a timer that calls the load_to_DB method every 30 minutes. But how to make it call the method every 30 minutes in synchronize with the system time? For example: at 12:35, then at 13:05, 13:35, 14:05 etc.

static void Main(string[] args)
    {
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 1800000;
        timer.Elapsed += load_to_DB;
        timer.Start();
        Console.ReadLine();
    }

    // This method is called every 30 mins
    static void load_to_DB(object sender, System.Timers.ElapsedEventArgs e)
    {
        //method
    }

Upvotes: 0

Views: 1210

Answers (2)

AliReza Sabouri
AliReza Sabouri

Reputation: 5215

try this if you need to manually set your start date and time :


private static DateTime _NextCallTime;
private static int MinSteps = 30;

static void Main(string[] args)
{
    // you can manually set start Date and Time
    _NextCallTime = DateTime.Parse ("2020/5/12 12:35");
    System.Timers.Timer timer = new System.Timers.Timer() 
            {Interval= 31000, Enabled = true}; 
    timer.Elapsed += timer_Handler;
    Console.ReadLine();
}

// this timer checks every 31 seconds
static void timer_Handler(object sender, System.Timers.ElapsedEventArgs e)
{
    if (DateTime.Now.Date == _NextCallTime.Date
       && DateTime.Now.Hour == _NextCallTime.Hour
       && DateTime.Now.Minute == _NextCallTime.Minute)
    {
        _NextCallTime = _NextCallTime.AddMinutes(MinSteps);         
        load_to_DB();
    }
    
}

// This method is called every 30 mins at spesific periods (12:35 - 1:5 ...)
static void load_to_DB()
{
    //method
}

also if you need to just set start time only, not the date:

// you can manually set start Time
_NextCallTime = DateTime.Parse($"{DateTime.Now.ToString("yyyy/MM/dd",System.Globalization.CultureInfo.InvariantCulture)} 12:35");

Upvotes: 1

Neil
Neil

Reputation: 11889

Obviously the timer you are using is an interval timer and will repeat every interval from whenever start is called.

One way to implement your schedule is to work out the different between now and the next time you want to schedule (e.g. at 12:02, you want to set the interval to 3 minutes, but at 12:05 you want to set the interval to be 30 minutes etc).

Upvotes: 0

Related Questions