[英]C# Timer on Elapsed Time does not call method
The below class is from a .Net Windows Service. 以下类来自.Net Windows服务。 The method DoSomeDatabaseStuff takes 10 minutes when it starts the first time but when the time is elapsed this method does not get called again. DoSomeDatabaseStuff方法在第一次启动时需要10分钟,但是当时间结束时,此方法不会再次被调用。
public class Test
{
public void Start()
{
DoSomeDatabaseStuff();
_oTimer = new Timer(60000);
_oTimer.Elapsed += OnTimeout;
_oTimer.AutoReset = true;
_oTimer.Start();
}
private void OnTimeout(object source, ElapsedEventArgs e)
{
DoSomeDatabaseStuff();
_oTimer = new Timer(60000);
_oTimer.Elapsed += OnTimeout;
_oTimer.AutoReset = true;
_oTimer.Start();
}
}
There are lots of serious problems in this code: 此代码中存在许多严重问题:
I use the System.Threading.Timer
in windows-services. 我在windows-services中使用System.Threading.Timer
。
Maybe this solves also your issue since others have also problems with the System.Timers.Timer
in windows-services: "What I've found is that System.Timers.Timer
just doesn't work in my Windows Service application. Therefore I've switched over to System.Threading.Timer
" 也许这也解决了你的问题,因为其他人也在Windows服务中的System.Timers.Timer
问题: “我发现System.Timers.Timer
在我的Windows服务应用程序中不起作用。所以我' ve切换到System.Threading.Timer
“
See: Windows Service System.Timers.Timer not firing 请参阅: Windows Service System.Timers.Timer未触发
private void InitService()
{
//starts immediately, interval is in TimeSpan
this._oTimer = new System.Threading.Timer(
OnTimeout,
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(10)
);
}
protected override void OnStart(string[] args)
{
InitService();
}
protected override void OnStop()
{
this._oTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
}
private void ImportTimer_Elapsed(Object state)
{
DoSomeDatabaseStuff();
}
Your program ends before timer could run. 您的程序在计时器运行之前结束。 Timer
is working in background thread witch is terminated when the main thread stops. Timer
正在后台线程中工作当主线程停止时终止。
try 尝试
static void Main(string[] args)
{
Test t = new Test();
t.Start();
Console.ReadLine();
}
Instead of creating a new timer every time, try setting the OnTimeout handler to: 不要每次都创建一个新的计时器,而是尝试将OnTimeout处理程序设置为:
_oTimer.Stop();
DoSomeDatabaseStuff();
_oTimer.Start();
similarly with the method Start(). 与方法Start()类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.