如何在特定时间运行.NET Core IHosted Service?

7
我正在使用以下计时器在 .Net Core IHosted Service 中运行:
TimeSpan ScheduledTimespan;
string[] formats = { @"hh\:mm\:ss", "hh\\:mm" };
string strTime = Startup.Configuration["AppSettings:JobStartTime"].ToString();
var success = TimeSpan.TryParseExact(strTime, formats, CultureInfo.InvariantCulture, out ScheduledTimespan);
Timer _timer = new Timer(JobToRun, null, TimeSpan.Zero, ScheduledTimespan);

我正在使用这个特定的重载函数,

public Timer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period);

但是JobToRun会在控制到达它的时候立即执行。 我该如何使其每天在特定时间运行? 提前感谢。


你有考虑过像 Coravel 这样的调度组件吗? - Aravind
没有,我会去找的。 - Sushant Yelpale
@Aravind 谢谢你的建议。我已经找到了解决方案。 - Sushant Yelpale
你可以在问题下添加你的答案。 - Aravind
1个回答

13
以下函数返回解析后的作业运行时间。
private static TimeSpan getScheduledParsedTime()
{
     string[] formats = { @"hh\:mm\:ss", "hh\\:mm" };
     string jobStartTime = "07:10";
     TimeSpan.TryParseExact(jobStartTime, formats, CultureInfo.InvariantCulture, out TimeSpan ScheduledTimespan);
     return ScheduledTimespan;
}

以下函数返回当前时间的延迟时间。如果当前时间已经超过作业运行时间,将会添加适当的延迟到作业运行中,如下所示:
private static TimeSpan getJobRunDelay()
{
    TimeSpan scheduledParsedTime = getScheduledParsedTime();
    TimeSpan curentTimeOftheDay = TimeSpan.Parse(DateTime.Now.TimeOfDay.ToString("hh\\:mm"));
    TimeSpan delayTime = scheduledParsedTime >= curentTimeOftheDay
        ? scheduledParsedTime - curentTimeOftheDay     // Initial Run, when ETA is within 24 hours
        : new TimeSpan(24, 0, 0) - curentTimeOftheDay + scheduledParsedTime;   // For every other subsequent runs
    return delayTime;
}

使用以下开销来实现每次执行后的24小时延迟:
_timer = new Timer(methodToExecute, null, getJobRunDelay(), new TimeSpan(24, 0, 0));

计时器将根据每天的JobRunDelay调用methodToExecute方法。

嗨,你觉得更新整个服务类可以吗?我的服务没有按照预期工作,无法找出问题所在。只是想对比一下你的服务类。 - DeSon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接