I have a method that send some SMS to our customers that look like below:
public void ProccessSmsQueue()
{
SmsDbContext context = new SmsDbContext();
ISmsProvider provider = new ZenviaProvider();
SmsManager manager = new SmsManager(context, provider);
try
{
manager.ProcessQueue();
}
catch (Exception ex)
{
EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}
finally
{
context.Dispose();
}
}
protected override void OnStart(string[] args)
{
Task.Factory.StartNew(DoWork).ContinueWith( ??? )
}
So, I have some issues:
I don´t know how long it takes for the method run;
The method can throw exceptions, that I want to write on EventLog
I want to run this method in loop, every 10 min, but only after last execution finish.
How I can achieve this? I thought about using ContinueWith()
, but I still have questions on how to build the entire logic.
You should have an async method that accepts a
CancellationToken
so it knows when to stop, callsProccessSmsQueue
in atry-catch
block and usesTask.Delay
to asynchronously wait until the next time it needs to run:You can call this method when your application starts and
Task.Wait
the returned task before existing so you know it completes and has no exceptions:Sample Worker Class that I have used in Windows Services. It supports stopping in a 'clean' way by using a lock. You just have to add your code in DoWork, set your timer in the StartTimerAndWork method (in milliseconds), and use this class in your service.