以下是一个示例代码,用于在每周三的中午12点执行某些操作:

private void StartTimer()
{
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = GetNextWednesdayNoon() - DateTime.Now; // 计算距离下一次周三中午12点的时间间隔
    timer.Tick += Timer_Tick;
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
    // 执行需要执行的操作

    // 重新启动定时器,以便在下一个周三中午12点再次执行
    DispatcherTimer timer = (DispatcherTimer)sender;
    timer.Interval = GetNextWednesdayNoon() - DateTime.Now;
    timer.Start();
}

private DateTime GetNextWednesdayNoon()
{
    // 计算下一个周三中午12点的时间
    DateTime nextWednesday = DateTime.Today.AddDays(1);
    while (nextWednesday.DayOfWeek != DayOfWeek.Wednesday)
    {
        nextWednesday = nextWednesday.AddDays(1);
    }
    return new DateTime(nextWednesday.Year, nextWednesday.Month, nextWednesday.Day, 12, 0, 0);
}

在上面的代码中,我们首先定义了一个 StartTimer 方法,该方法会创建一个 DispatcherTimer 实例,并设置定时器的 Interval 属性为距离下一个周三中午12点的时间间隔。然后,我们将 Tick 事件处理程序绑定到定时器的 Tick 事件,以便在定时器触发时执行需要执行的操作。在 Tick 事件处理程序中,我们首先执行需要执行的操作,然后重新计算距离下一个周三中午12点的时间间隔,并将其设置为定时器的 Interval 属性。最后,我们重新启动定时器,以便在下一个周三中午12点再次触发。 GetNextWednesdayNoon 方法用于计算下一个周三中午12点的时间

C# WPF dispatcherTimerInterval 定时器每周三 12点执行一次

原文地址: https://www.cveoy.top/t/topic/htpd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录