1、通过线程操作
static void Main(string[] args)
{
Console.WriteLine("检测程序启动运行,自动启动或停止网站及应用池。");
new Thread(RecoveryWebSite).Start();
}
public static void RecoveryWebSite()
{
const string AppPoolName = "";
const string WebSiteName = "";
const int SleepTime = 1000 * 30;
ServerManager sm = new ServerManager();
while (true)
{
try
{
var pool = sm.ApplicationPools[AppPoolName];
if (pool != null)
{
if (pool.State == ObjectState.Stopped)
{
WriteLog("检测到应用池" + AppPoolName + "停止服务");
WriteLog("正在启动应用池" + AppPoolName);
if (pool.Start() == ObjectState.Started)
{
WriteLog("成功启动应用池" + AppPoolName);
}
else
{
WriteLog("启动应用池" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动");
}
}
else if (pool.State == ObjectState.Started)
{
if (pool.Stop() == ObjectState.Stopped)
{
WriteLog("成功停止应用池" + AppPoolName);
}
else
{
WriteLog("停止应用池" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动");
}
}
}
Site site = sm.Sites[WebSiteName];
if (site != null)
{
if (site.State == ObjectState.Stopped)
{
WriteLog("检测到网站" + WebSiteName + "停止服务");
WriteLog("正在启动网站" + WebSiteName);
if (site.Start() == ObjectState.Started)
{
WriteLog("成功启动网站" + WebSiteName);
}
else
{
WriteLog("启动网站" + WebSiteName + "失败. " + SleepTime / 60 + "秒后重试启动");
}
}
else if (site.State == ObjectState.Started)
{
if (site.Stop() == ObjectState.Stopped)
{
WriteLog("成功停止网站" + AppPoolName);
}
else
{
WriteLog("停止网站" + AppPoolName + "失败. " + SleepTime / 60 + "秒后重试启动");
}
}
}
}
catch (Exception ex)
{
WriteLog(ex.Message.ToString());
}
GC.Collect();
Thread.Sleep(SleepTime);
}
}
public static void WriteLog(string msg)
{
var fPath = "C:\\Users\\Administrator\\Desktop\\更新日志.txt";
if (!File.Exists(fPath))
{
File.Create(fPath).Close();
}
using (StreamWriter sw = new StreamWriter(fPath, true, Encoding.UTF8))
{
sw.WriteLine(string.Format("{0} , 时间{1}", msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
}
}
2、通过定时器操作
static ServerManager serverManager;
static System.Configuration.Configuration config;
static int SleepTime;
static System.Timers.Timer timer;
static void Main(string[] args)
{
Console.WriteLine("检测程序启动运行,自动启动或停止网站及应用池。");
serverManager = new ServerManager();
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
SleepTime = int.Parse(config.AppSettings.Settings["SleepTime"].Value);
timer timer = new System.Timers.Timer();
timer.Interval = SleepTime;
timer.Elapsed += new System.Timers.ElapsedEventHandler(RecoveryWebSite);
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
while (true) { }
}
public static void RecoveryWebSite(object sender, System.Timers.ElapsedEventArgs e)
{
}