我正在使用每 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(); }}
2 回答

吃鸡游戏
TA贡献1829条经验 获得超7个赞
为什么不简单地在计时器之上调用构造函数中的代码(立即拥有它)?
_Timer = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds)
{
Enabled = true
};
// add this
ExecuteEvery5Min();
_Timer.Elapsed += (sender, eventArgs) =>
{
ExecuteEvery5Min();
};

慕无忌1623718
TA贡献1744条经验 获得超4个赞
如果可以的话,您可以改用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
- 2 回答
- 0 关注
- 101 浏览
添加回答
举报
0/150
提交
取消