diff --git a/Web/Global.asax.cs b/Web/Global.asax.cs index f9712ab..7ca54a9 100644 --- a/Web/Global.asax.cs +++ b/Web/Global.asax.cs @@ -45,6 +45,13 @@ namespace MileageTraker.Web ModelMetadataProviders.Current = new CustomMetadataProvider(); LogManager.GetCurrentClassLogger().Info("Application_Start()"); + + HangfireBootstrapper.Instance.Start(); + } + + protected void Application_End(object sender, EventArgs e) + { + HangfireBootstrapper.Instance.Stop(); } } diff --git a/Web/Startup.cs b/Web/Startup.cs index a3c1242..edece4f 100644 --- a/Web/Startup.cs +++ b/Web/Startup.cs @@ -1,10 +1,12 @@ using System; +using System.Web.Hosting; using Hangfire; using Microsoft.Owin; +using MileageTraker.Web; using MileageTraker.Web.Email; using Owin; -[assembly: OwinStartup(typeof(MileageTraker.Web.Startup))] +[assembly: OwinStartup(typeof (Startup))] namespace MileageTraker.Web { @@ -13,7 +15,7 @@ namespace MileageTraker.Web public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration - .UseSqlServerStorage("MileageTrakerContext"); + .UseSqlServerStorage("MileageTrakerContext"); app.UseHangfireDashboard(); app.UseHangfireServer(); @@ -27,4 +29,62 @@ namespace MileageTraker.Web "serviceReminderJob", s => s.SendAllNotificationEmails(), Cron.Weekly(DayOfWeek.Monday, 6)); } } + + // http://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html + public class ApplicationPreload : IProcessHostPreloadClient + { + public void Preload(string[] parameters) + { + HangfireBootstrapper.Instance.Start(); + } + } + + public class HangfireBootstrapper : IRegisteredObject + { + public static readonly HangfireBootstrapper Instance = new HangfireBootstrapper(); + + private readonly object _lockObject = new object(); + private bool _started; + + private BackgroundJobServer _backgroundJobServer; + + private HangfireBootstrapper() + { + } + + public void Start() + { + lock (_lockObject) + { + if (_started) return; + _started = true; + + HostingEnvironment.RegisterObject(this); + + GlobalConfiguration.Configuration + .UseSqlServerStorage("MileageTrakerContext"); + // Specify other options here + + _backgroundJobServer = new BackgroundJobServer(); + } + } + + public void Stop() + { + lock (_lockObject) + { + if (_backgroundJobServer != null) + { + _backgroundJobServer.Dispose(); + } + + HostingEnvironment.UnregisterObject(this); + } + } + + void IRegisteredObject.Stop(bool immediate) + { + Stop(); + } + } } \ No newline at end of file diff --git a/Web/Web.csproj b/Web/Web.csproj index ba23acb..afce9d0 100644 --- a/Web/Web.csproj +++ b/Web/Web.csproj @@ -343,6 +343,9 @@ + + PreserveNewest + Always @@ -616,7 +619,6 @@ -