创建一个倒计时计时器,直到计时器开始

本文关键字:计时器 开始 倒计时 一个 创建 | 更新日期: 2023-09-27 18:15:10

我在控制台应用程序中有一个计时器:

using System.Timers;
Timer Timer = new Timer();

我给它一个interval,它周期性地在_timer_Elapsed方法做一些事情:

Timer.Elapsed += _timer_Elapsed;
Timer.Enabled = true;
private static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
    ...
}

我如何创建第二个计时器倒计时,直到这个计时器开始?

创建一个倒计时计时器,直到计时器开始

创建一个每秒运行一次的第二个计时器,并使用以下代码倒数并向控制台写入消息。

#define COUNTDOWN_SECONDS 10
private int CountDownValue = COUNTDOWN_SECONDS;
private static void _timer2_Elapsed(object sender, ElapsedEventArgs e)
{
    WriteConsoleMessage(CountDownValue--);
    if (CountDownValue == 0)
    {
        // Stop timer2
        // Start timer1
    }
}
private static void WriteConsoleMessage(int Value)
{
    if (Value < COUNTDOWN_SECONDS)
        Console.CursorLeft = 0;  // Reset cursor to start of the line
    Console.Write(string.Format("{0} Seconds until timer starts", Value.ToString());
}

我是这样做的:

    public static int Interval = 5000;
    public static int IntervalLeft = Interval;

            Timer.Elapsed += _timer_Elapsed;
            Timer.Enabled = true;
            Timer.Interval = Interval;
            CountDownTimer.Elapsed += _CountDowntimer_Elapsed;
            CountDownTimer.Enabled = true;
            CountDownTimer.Interval = 1000;
            CountDownTimer.Start();

    private static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        CountDownTimer.Stop();
        Timer.Stop();
         DOES THE JOB HERE

        Timer.Start();
        CountDownTimer.Start();
        IntervalLeft = Interval;
    }

   private static void _CountDowntimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Zipper.ClearCurrentConsoleLine();
        IntervalLeft = (IntervalLeft - 1000);
        Console.Write("Starts in" + IntervalLeft/1000);
    }