C# 可以使用 System.Threading.Timer 类实现每日定时任务。

以下是一个示例代码:

using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        // 设置每天执行时间
        TimeSpan scheduledTime = new TimeSpan(8, 0, 0);

        // 计算下一次执行时间
        DateTime scheduledDateTime = DateTime.Today.Add(scheduledTime);
        if (scheduledDateTime < DateTime.Now)
        {
            scheduledDateTime = scheduledDateTime.AddDays(1);
        }

        // 计算下一次执行时间与当前时间的时间间隔
        TimeSpan timeToGo = scheduledDateTime - DateTime.Now;

        // 创建定时器
        Timer timer = new Timer(x =>
        {
            // 执行定时任务
            // ...

            // 计算下一次执行时间
            scheduledDateTime = scheduledDateTime.AddDays(1);

            // 重新计算下一次执行时间与当前时间的时间间隔
            timeToGo = scheduledDateTime - DateTime.Now;

            // 重新启动定时器
            timer.Change(timeToGo, TimeSpan.FromDays(1));
        }, null, timeToGo, TimeSpan.FromDays(1));

        // 等待用户按下回车键退出程序
        Console.ReadLine();
    }
}

在上面的示例代码中,我们设置了每天的执行时间为 8:00:00,然后计算下一次执行时间与当前时间的时间间隔,创建了一个定时器,定时器的回调函数中执行定时任务,然后重新计算下一次执行时间与当前时间的时间间隔,重新启动定时器。定时器的第一个参数 x 是一个 object 类型的参数,可以在回调函数中使用。定时器的第二个参数是一个 state 参数,可以在回调函数中使用,这里我们没有使用。定时器的第三个参数是延迟多长时间开始执行,我们设置为时间间隔 timeToGo。定时器的第四个参数是执行间隔,我们设置为一天。最后,我们等待用户按下回车键退出程序。

C# 实现每日定时任务

原文地址: https://www.cveoy.top/t/topic/BDF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录