有没有一种方法可以在应用程序立即启动时执行 ExecuteEvery5Min 方法

我正在使用每 5 分钟Timer调用一段代码的方法。ExecuteEvery5Min


现在我启动控制台应用程序,我必须等待 5 分钟,然后ExecuteEvery5Min执行代码,然后每 5 分钟执行一次......


有没有办法在应用程序启动并立即ExecuteEvery5Min执行代码然后每 5 分钟通过计时器执行一次?


using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use

        {

            while (true) { }

        }



public class UtilityClass : IDisposable

{

    private readonly System.Timers.Timer _Timer;


    public UtilityClass()

    {

        _Timer = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds)

        {

            Enabled = true

        };


        _Timer.Elapsed += (sender, eventArgs) =>

        {

            ExecuteEvery5Min();

        };

    }


    private void ExecuteEvery5Min()

    {

        Console.WriteLine($"Every 5 minute at {DateTime.Now}");

    }


    public void Dispose()

    {

        _Timer.Dispose();

    }

}


哔哔one
浏览 102回答 2
2回答

吃鸡游戏

为什么不简单地在计时器之上调用构造函数中的代码(立即拥有它)?    _Timer = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds)    {        Enabled = true    };    // add this    ExecuteEvery5Min();    _Timer.Elapsed += (sender, eventArgs) =>    {        ExecuteEvery5Min();    };

慕无忌1623718

如果可以的话,您可以改用System.Threading.Timer它,它具有以下构造函数:public Timer (System.Threading.TimerCallback callback, object state, int dueTime, int period);从以下链接引用:dueTime Int32 调用回调之前延迟的时间量,以毫秒为单位。指定 Infinite 以防止计时器启动。指定零 (0) 以立即启动计时器。period Int32 回调调用之间的时间间隔,以毫秒为单位。指定 Infinite 以禁用周期性信号。PS:它是基于回调的,而不是像你现在使用的那样基于事件。请参阅:https ://learn.microsoft.com/en-us/dotnet/api/system.threading.timer.-ctor?view=netframework-4.8
打开App,查看更多内容
随时随地看视频慕课网APP