[C#]每隔一段時間檢察網站是否 Service Unavailable 和重新啟動
2020-11-06
工具:Visual Studio 2019
架構:C# .NET Framework + ConsoleApp
某個網站,每隔一段時間會出現
Service Unavailable
HTTP Error 503. The service is unavailable.
IIS 服務重新啟動無效,必須整個 Windows 重新啟動。
事件檢視器顯示 IIS 發生 Error 事件,但看不出到底哪個網頁程式或哪一段程式出錯。
Elmah 根本攔截不到 Exception
所以想寫個程式處理,因為排程無法設定每 5 分鐘執行一次
using System; using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WWWSiteCheckAndRestart
{
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
// 1秒=1000毫秒,預計5分鐘監控一次
System.Threading.Timer threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(obj.Method3), null, 0, 5*60*1000);
// 測試觸發狀況
//while (true)
//{
// //Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString());
// //Console.WriteLine(DateTime.Now.ToString());
// Thread.Sleep(100);
//}
Console.ReadLine();
}
void Method3(Object state)
{
//Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString());
// 忽略 https 憑證驗證
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
// 讀取網頁內容
string html = string.Empty;
string url = "https://localhost";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "C# console client";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
if (html.Contains("Service Unavailable"))
{
System.Diagnostics.Process.Start("C:\\WINDOWS\\system32\\shutdown.exe", "-f -r -t 0");
}
//Console.WriteLine(html);
}
}
}
|
Micro Focus Fortify Static Code Analyzer ( SCA ) 掃描沒發現問題。
(完)
沒有留言:
張貼留言