using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using Hangfire;
using Hangfire.Logging;
using Microsoft.Owin;
using Owin;
using Hangfire.SQLite;
[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
//REF: https://github.com/HangfireIO/Hangfire.AspNet
publicclass Startup : IRegisteredObject
{
public Startup()
{
HostingEnvironment.RegisterObject(this);
}
privatestaticreadonlystring SqliteDbPath =
HostingEnvironment.MapPath("~/App_Data/Hangfire.sqlite");
privatestatic BackgroundJobServer backJobServer = null;
publicstatic IEnumerable<IDisposable> GetHangfireConfiguration()
{
GlobalConfiguration.Configuration
.UseSQLiteStorage($"Data Source={SqliteDbPath};");
backJobServer = new BackgroundJobServer(
new BackgroundJobServerOptions
{
ServerName =
$"JobServer-{Process.GetCurrentProcess().Id}"
});
yieldreturn backJobServer;
}
publicvoid Configuration(IAppBuilder app)
{
//改用UseHangfireAspNet設定Hangfire服務
app.UseHangfireAspNet(GetHangfireConfiguration);
app.UseHangfireDashboard();
ScheduledTasks.Setup();
}
//ApplicationPool結束時會呼叫
publicvoid Stop(bool immediate)
{
//Thread.Sleep(TimeSpan.FromSeconds(30));
//Github範例等待30秒,會影響AppPool停止及回收速度
//這裡改為直接呼叫backJobServer.Dispose()
if (backJobServer != null)
{
backJobServer.Dispose();
}
HostingEnvironment.UnregisterObject(this);
}
}
}