如果您需要更复杂的时间执行,例如 linux cron,可以使用 NCrontab。
我在生产中使用 NCrontab 很长时间了,效果很好!
努吉特
如何使用:
* * * * *
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
using NCrontab;
//...
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// run every 5 minutes
var schedule = CrontabSchedule.Parse("*/5 * * * *");
var nextRun = schedule.GetNextOccurrence(DateTime.Now);
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
do
{
if (DateTime.Now > nextRun)
{
logger.LogInformation("Sending notifications at: {time}", DateTimeOffset.Now);
await DoSomethingAsync();
nextRun = schedule.GetNextOccurrence(DateTime.Now);
}
await Task.Delay(1000, stoppingToken);
} while (!stoppingToken.IsCancellationRequested);
}
如果需要,请添加秒数:
// run every 10 secs
var schedule = CrontabSchedule.Parse("0/10 * * * * *", new CrontabSchedule.ParseOptions { IncludingSeconds = true });