I have 2 alternatives for executing recurring tasks in ASP.NET MVC.
We just need to add some code in Global.asax
First alternative:
private static void ThreadSendNextMail()
{
while (true)
{
HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
using (var db = new EFDbContext())
{
try
{
//demo test for periodically tasks
int paymentCount = await db.Payments.AsNoTracking().CountAsync();
logger.Info(paymentCount);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
}
}
});
Thread.Sleep(20000);
}
}
private Thread mailThread { get; set; }
protected void Application_Start()
{
//other code removed for clarity
mailThread = new Thread(new ThreadStart(ThreadSendNextMail));
mailThread.Start();
}
Second alternative:
private void AddTask(Action<string, object, CacheItemRemovedReason> target, int seconds)
{
HttpRuntime.Cache.Insert(target.Method.Name + DateTime.Now.ToString(), seconds, null, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(target));
}
public void SendNextMail(string key, object seconds, CacheItemRemovedReason reason)
{
HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
using (var db = new EFDbContext())
{
try
{
//demo test for periodically tasks
int paymentCount = await db.Payments.AsNoTracking().CountAsync();
logger.Info(paymentCount);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
}
}
});
AddTask(SendNextMail, Convert.ToInt32(seconds));
}
protected void Application_Start()
{
//other code removed for clarity
//Periodically tasks
AddTask(SendNextMail, 20);
}
I use .NET 4.5.2 and MVC 5.2. For logging I use NLog.
Both methods work perfectly (You can check this by watch log time in log file). Which is more preferable and better for performance, if I have many recurring tasks in the same time?
Do you see any improvement / issue?