Home > Enterprise >  Trigger BackgroundWorker at a specific point in time
Trigger BackgroundWorker at a specific point in time

Time:08-12

I try to create a windows service to check my data has expired.

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        TimeSpan now = DateTime.Now.TimeOfDay;
        if (now.Hours == 14 & now.Minutes == 37 & now.Seconds == 0)
        {
            //do something...
        }
    }
}

I found this BackgroundWorker always check the current time.

Is this the correct way to use it?

CodePudding user response:

This loop will run continuously. If you want to run the background worker at a specific point in time then you can either make the thread sleep for the specific amount of time (Target time - current time) or a fixed interval before it polls for the execution window. Keep in mind that when you choose the latter you should allow the execution happen within a window than the exact time. Otherwise, the task may never execute!

CodePudding user response:

Thanks to Mayur Ekbote for giving me ideas.

Here is my solution:

while (!stoppingToken.IsCancellationRequested)
{
    DateTime now = DateTime.Now;
    DateTime work_point = new DateTime(now.Year, now.Month, now.Day, 18, 33, 00);
    if (work_point < now)
    {
        work_point = work_point   new TimeSpan(24,0,0);
    }
    DateTime start_check_point = work_point - new TimeSpan(0, 1, 0);
    DateTime end_check_point = work_point   new TimeSpan(0, 1, 0);
    if (now >= start_check_point && now <= end_check_point)
    {
        _logger.LogInformation("start program at {time}", DateTimeOffset.Now);
        try
        {
            //do something...
        }
        catch (Exception ex)
        {
            _logger.LogError("error msg", ex.Message);
        }
        finally
        {
            //Skip inspection period interval
            await Task.Delay(1000 * 60, stoppingToken);
        }
    }
    else
    {
        _logger.LogError($"Scheduled to run at {work_point.ToString("s")} ");
         //Pause the program until the check interval to avoid wasting performance
        await Task.Delay(start_check_point - now, stoppingToken);
    }
}
  • Related