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