0
       private void WorkerThread()
    {
        AppConsole.Log("Restarter Worker Thread Started", ConsoleColor.Green);
        DateTime nextRestart = GetRestartTime(); //--- Fetch next restart
        AppConsole.Log(String.Format("Selected next restart date: {0}", nextRestart.ToString("F")), ConsoleColor.Green);
        _workerRunning = true;

        while (_workerRunning) {
            _waitHandle.WaitOne(1000);
            TimeSpan timeLeft = nextRestart.Subtract(DateTime.Now);
            SendMessage(String.Format("Time until next restart: {0} hours, {1} minutes, {2} seconds.",
                timeLeft.Hours, timeLeft.Minutes, timeLeft.Seconds));
            if (timeLeft.CompareTo(TimeSpan.Zero) < 0)
                DoRestart();
        }

基本上从这个线程中,如果服务器距离重新启动超过 10 分钟,我需要每 5 分钟输出一条消息,如果服务器距离启动不到 10 分钟,我需要每 2.5 分钟输出一条消息。我只是想知道这样做的最佳方法是什么。

干杯

4

1 回答 1

0

你不需要一个线程,你需要一个计时器。

    DateTime nextRestart = GetRestartTime();
    AppConsole.Log("Restarter timer started", ConsoleColor.Green);
    Timer t = new Timer();
    t.Tick += (o, e) =>
    {
        TimeSpan timeLeft = nextRestart.Subtract(DateTime.Now);

        if (timeLeft.CompareTo(TimeSpan.Zero) < 0)
        {
            t.Stop();
            DoRestart();
        }
        else
        {
            SendMessage(String.Format("Time until next restart: {0} hours, {1} minutes, {2} seconds.",
                timeLeft.Hours, timeLeft.Minutes, timeLeft.Seconds));
            if (timeLeft.CompareTo(TimeSpan.FromMinutes(5)) < 0)
                t.Interval = 150 * 60 * 1000; // ms
            else if (timeLeft.CompareTo(TimeSpan.FromMinutes(10)) < 0)
                t.Interval = 300 * 60 * 1000; // ms
        }
    };
    t.Interval = (nextRestart - DateTime.Now).Milliseconds;
    t.Start();

您需要的所有代码都在一个整洁的包中。你甚至可以将它包装在一个类中。

于 2015-08-14T22:02:49.290 回答