需求回顧
- 07:00-08:00、11:00-12:00 播放 A 程序
- 09:00-10:00 打開 B 程序
- 13:00-14:00 輪播 5 個網頁,每頁 3 分鐘
推薦架構:單主窗體 + 任務調度器
public class Scheduler {
private readonly Dictionary _states = new();
private readonly WebBrowser _browser = new WebBrowser(); // 內嵌瀏覽器
private int _webIndex = 0;
private readonly string[] _webUrls = new string[5]; // 從配置讀取
public void Start() {
var timer = new System.Windows.Forms.Timer { Interval = 1000 };
timer.Tick += (s, e) => CheckAndExecute();
timer.Start();
}
private void CheckAndExecute() {
var now = DateTime.Now.TimeOfDay;
// A 程序時段
if (InRange(now, "07:00", "08:00") || InRange(now, "11:00", "12:00")) {
ExecuteOnce("TaskA", () => Process.Start("A.exe"));
}
// B 程序時段
if (InRange(now, "09:00", "10:00")) {
ExecuteOnce("TaskB", () => Process.Start("B.exe"));
}
// 網頁輪播時段
if (InRange(now, "13:00", "14:00")) {
ExecuteWebRotation();
}
}
private bool InRange(TimeSpan now, string start, string end) {
return now >= TimeSpan.Parse(start) && now < TimeSpan.Parse(end);
}
private void ExecuteOnce(string key, Action action) {
if (_states.TryGetValue(key, out var st) && st.ExecutedToday) return;
action();
_states[key] = new TaskState { ExecutedToday = true, Date = DateTime.Today };
}
private void ExecuteWebRotation() {
if (_browser.Document == null || _webIndex >= _webUrls.Length) return;
_browser.Navigate(_webUrls[_webIndex]);
_webIndex = (_webIndex + 1) % _webUrls.Length;
// 3 分鐘後觸發下一輪,可用 Timer 或 Navigated 事件鏈
}
}
class TaskState { public bool ExecutedToday; public DateTime Date; }
關鍵優勢
- 無需多子窗體,UI 簡單、內存佔用低。
- 內嵌
WebBrowser (IE 內核) 或 WebView2 (Edge Chromium) 可程序化控制導航、監聽加載完成、無彈窗干擾。
- URL 存
App.config / appsettings.json,修改無需重編譯。
- 狀態字典自動按日期重置,跨天自動執行。
配置文件示例
<appSettings>
<add key="WebUrl1" value="https://site1.com" />
<add key="WebUrl2" value="https://site2.com" />
...
</appSettings>