简体   繁体   English

.Net Core 6 创建调度任务

[英].Net Core 6 Create Scheduling Task

I have a .Net Core 6 project and I want do schedule some task working at every day 09:00 am.我有一个 .Net Core 6 项目,我想在每天上午 9:00 安排一些任务。

What is the best way for task scheduler?任务调度程序的最佳方式是什么?

Note: Hangfire is good solution but it is working with DataBase, this is bad for my project.注意:Hangfire 是一个很好的解决方案,但它与数据库一起使用,这对我的项目不利。

You can work with timers .您可以使用计时器

static DateTime GetNextRunTime()
{
    DateTime now = DateTime.Now;
    if (now.Hour < 9)
    {
        // If time of the day is before 9:00 am, then job will run today at 9
        // Using this way instead of DateTime.Today.AddHours(9) because it can cause weird issues with Daylight Saving when time offset changes
        return new DateTime(now.Year, now.Month, now.Day, 9, 0, 0);
    }
    // Job will run tommorow at 9:00
    DateTime tomorrow = DateTime.Today.AddDays(1);
    return new DateTime(tomorrow .Year, tomorrow .Month, tomorrow .Day, 9, 0, 0);
}

static void ScheduleNextJob(Action action)
{
    var dueTime = GetNextRunTime() - DateTime.Now;
    
    System.Threading.Timer timer = null;
    timer = new Timer(() => 
    {
        // run your code
        try
        {
             action();
        }
        catch
        {
              // Handle the exception here, but make sure next job is scheduled if an exception is thrown by your code.
        }
        ScheduleNextJob(action); // Schedule next job
        timer?.Dispose(); // Dispose the timer for the current job
    }, null, dueTime, TimeSpan.Infinite);
}

The reason for creating a new timer everytime we schedule a job rather than have a timer with 24 hours period is again Daylight saving.每次我们安排作业而不是使用 24 小时周期的计时器时都创建一个新计时器的原因再次是夏令时。 On days the time changes from summer to winter or vice versa, the difference between 9am and 9am next day is not 24 hours.在日子里,时间从夏季变为冬季,反之亦然,早上 9 点和第二天早上 9 点之间的时间差不是 24 小时。

NET 6 has built in support for recurring tasks and you can build a windows service pretty easily. NET 6 内置了对重复任务的支持,您可以非常轻松地构建 Windows 服务。 Building this as a windows service means that once you've installed it you don't have to worry about a reboot because you can tell the service to start on reboot.将其构建为 Windows 服务意味着一旦您安装了它,您就不必担心重新启动,因为您可以告诉服务在重新启动时启动。

Checkout Create a Windows Service using BackgroundService Checkout 使用 BackgroundService 创建 Windows 服务

andWorker Services in .NET.NET 中的 Worker 服务

Your total reading time would be about 20 minutes, so it is pretty straight forward.您的总阅读时间约为 20 分钟,因此非常简单。 It is a bit too involved to explain fully in a Stack Overflow answer.在 Stack Overflow 答案中完全解释有点太复杂了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM