public class JobHost : IRegisteredObject
{
private readonly object _lock = new object();
private bool _shuttingDown;
public JobHost()
{
HostingEnvironment.RegisterObject(this);
}
public void Stop(bool immediate)
{
lock (_lock)
{
_shuttingDown = true;
}
HostingEnvironment.UnregisterObject(this);
}
public void DoWork(Action work)
{
lock (_lock)
{
if (_shuttingDown)
{
return;
}
work();
}
}
}
public static class MyHelper
{
private static readonly Timer _timer = new Timer(OnTimerElapsed);
private static readonly JobHost _jobHost = new JobHost();
public static void Start()
{
_timer.Change(TimeSpan.Zero, TimeSpan.FromHours(1));
}
public static void OnTimerElapsed(object sender)
{
_jobHost.DoWork(() =>
{
// action ...
});
}
}
public class Application : HttpApplication
{
protected void Application_Start()
{
// ....
MyHelper.Start();
}
}
Log_app.Info("Checking database...");
using (var ctx = new ApplicationDbCtx())
{
if (!ctx.Database.Exists() || !ctx.Database.CompatibleWithModel(false))
{
try
{
Log_app.Info("updating Database ...");
Database.SetInitializer<ApplicationDbCtx>(new MigrateDatabaseToLatestVersion<ApplicationDbCtx, MyApplication.Migrations.Configuration>());
ctx.Database.Initialize(true);
}
catch (Exception ex)
{
Log_app.Error(ex);
}
}
}
Log_app.Info("checking Database completed!");