vs新建Windows服务:
双击Service打开代码视图:
Logger配置
partial class RecoveryWebSiteService : ServiceBase
{
private Thread MainThread;
static readonly string AppPoolName1 = ConfigurationManager.AppSettings["ApplicationPoolName1"].ToString();
static readonly string AppPoolName2 = ConfigurationManager.AppSettings["ApplicationPoolName2"].ToString();
static readonly string WebSiteName1 = ConfigurationManager.AppSettings["WebSiteName1"].ToString();
static readonly string WebSiteName2 = ConfigurationManager.AppSettings["WebSiteName2"].ToString();
static readonly int SleepTime = int.Parse(ConfigurationManager.AppSettings["SleepTime"].ToString());
static ServerManager sm = new ServerManager();
public RecoveryWebSiteService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
MainThread = new Thread(new ThreadStart(ThreadProc));
MainThread.Start();
}
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
}
private void ThreadProc()
{
while (true)
{
try
{
//国庆、中秋等重大节日会手动关闭,不用开启
var month = DateTime.Now.Month;
var day = DateTime.Now.Day;
var dtStr = (month < 10 ? ("0" + month) : month.ToString())
+ (day < 10 ? ("0" + day) : day.ToString());
var holidayList = HolidayEnum.holiday.ToList();
if (!holidayList.Contains(dtStr))
{
var pool1 = sm.ApplicationPools[AppPoolName1];
var pool2 = sm.ApplicationPools[AppPoolName2];
var site1 = sm.Sites[WebSiteName1];
var site2 = sm.Sites[WebSiteName2];
StartPool(AppPoolName1, pool1, site1);
StartPool(AppPoolName2, pool2, site2);
StartWebSite(WebSiteName1, site1);
StartWebSite(WebSiteName2, site2);
//每天凌晨两点定时重启应用池和网站
if (DateTime.Now.Hour == 2)
{
Logger.Write(typeof(RecoveryWebSiteService), "定时重启应用池和网站");
pool1.Start();
site1.Start();
pool2.Start();
site2.Start();
}
}
}
catch (Exception ex)
{
Logger.Write(typeof(RecoveryWebSiteService), ex);
}
GC.Collect();
Thread.Sleep(SleepTime);
}
}
private void StartPool(string poolName, ApplicationPool pool, Site site)
{
if (pool != null && pool.State == ObjectState.Stopped)
{
Logger.Write(typeof(RecoveryWebSiteService), "检测到应用池" + poolName + "停止服务");
Logger.Write(typeof(RecoveryWebSiteService), "正在启动应用池" + poolName);
if (pool.Start() == ObjectState.Started)
{
Logger.Write(typeof(RecoveryWebSiteService), "成功启动应用池" + poolName);
site.Start();
}
else
{
Logger.Write(typeof(RecoveryWebSiteService), "启动应用池" + poolName + "失败。" + SleepTime + "分钟后重试启动");
}
}
}
private void StartWebSite(string siteName, Site site)
{
if (site != null && site.State == ObjectState.Stopped)
{
Logger.Write(typeof(RecoveryWebSiteService), "检测到网站" + siteName + "停止服务");
Logger.Write(typeof(RecoveryWebSiteService), "正在启动网站" + siteName);
if (site.Start() == ObjectState.Started)
{
Logger.Write(typeof(RecoveryWebSiteService), "成功启动网站" + siteName);
}
else
{
Logger.Write(typeof(RecoveryWebSiteService), "启动网站" + siteName + "失败。 " + SleepTime + "分钟后重试启动");
}
}
}
}