I used the information from the article "Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)" to create a background task that runs on an infinite loop. Ultimately, this program is going to be consuming a REST API to get data from a remote web site and insert records into my database. For the time being, I am just doing a basic insert.
public class PreWarmCache : System.Web.Hosting.IProcessHostPreloadClient
{
private static BackgroundTaskContext db = new BackgroundTaskContext();
private static Timer _timer;
public void Preload(string[] parameters)
{
// Perform initialization and cache loading logic here...
try
{
var doStuff = new DoStuff();
doStuff.DoStuffName = "Test from PRELOAD INIT " + DateTime.Now;
db.DoStuffs.Add(doStuff);
db.SaveChanges();
}
catch
{
}
var timeInMilliseconds = 0;
_timer = new Timer(Callback, null, timeInMilliseconds, Timeout.Infinite);
}
public static void Callback(Object state)
{
var timeInMilliseconds = 5000;
Stopwatch watch = new Stopwatch();
watch.Start();
// Update the database
try
{
var doStuff = new DoStuff();
doStuff.DoStuffName = "Test from CALLBACK " + DateTime.Now;
db.DoStuffs.Add(doStuff);
db.SaveChanges();
}
catch
{
}
_timer.Change(Math.Max(0, timeInMilliseconds - watch.ElapsedMilliseconds), Timeout.Infinite);
}
}