The below class is from a .Net Windows Service. 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.
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.
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
"
See: Windows Service System.Timers.Timer not firing
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.
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:
_oTimer.Stop();
DoSomeDatabaseStuff();
_oTimer.Start();
similarly with the method Start().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.