我使用的是一个Timer,它每5分钟调用一段代码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();
}
}发布于 2019-04-22 09:04:10
如果可以的话,您可以使用System.Threading.Timer代替,它有以下构造函数:
public Timer (System.Threading.TimerCallback callback, object state, int dueTime, int period);引用以下链接:
调用回调之前的延迟时间(以毫秒为单位)。指定“无限”以防止计时器启动。指定0 (0)立即启动定时器。 周期 Int32回调调用之间的时间间隔,以毫秒为单位。指定“无限”可禁用周期性信号。
PS:它是基于回调的,而不是像你现在使用的那样基于事件的。
请参阅:https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer.-ctor?view=netframework-4.8
https://stackoverflow.com/questions/55791771
复制相似问题