You need to enable JavaScript to run this app. C# WinForm Timer实现等待8小时后到早8点启动exe并自动退出
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm Timer实现等待8小时后到早8点启动exe并自动退出

逻辑实现说明

原有代码的核心问题

  • 未实现「程序启动后先等待8小时再进行时间判断」的前置流程,当前代码一启动Timer就会立刻触发判断
  • else分支无等待逻辑,无论是否到达早8点都会直接启动Alarm.exe

修改后完整可运行代码

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace Timer
{
    public partial class Timer : Form
    {
        // 前置等待时长:固定8小时
        private readonly TimeSpan PreWaitHours = TimeSpan.FromHours(8);
        // 目标启动时间点:每日早8点
        private readonly TimeSpan Morning8 = TimeSpan.FromHours(8);

        public Timer()
        {
            InitializeComponent();
            // 初始化时关闭Timer,避免启动即触发流程
            timer1.Enabled = false;
        }

        private void Timer_Load(object sender, EventArgs e)
        {
            // 程序启动后先等待8小时,设置Timer的触发间隔为8小时对应的毫秒数
            timer1.Interval = (int)PreWaitHours.TotalMilliseconds;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // 每次触发先关闭Timer,防止重复执行
            timer1.Stop();
            DateTime now = DateTime.Now;
            TimeSpan currentTime = now.TimeOfDay;

            if (currentTime >= Morning8)
            {
                // 已到达早8点及之后时段,直接启动目标程序
                Process.Start(@"Alarm.exe");
                // 自动退出自身程序
                Application.Exit();
            }
            else
            {
                // 未到早8点,计算距离当日早8点的剩余等待时长
                DateTime target8Am = now.Date.Add(Morning8);
                TimeSpan remainWaitTime = target8Am - now;
                // 设置Timer为剩余等待时长,到点自动触发
                timer1.Interval = (int)remainWaitTime.TotalMilliseconds;
                timer1.Start();
            }
        }
    }
}

新手注意事项

  • 不要使用Thread.Sleep()实现长时间等待,该方法会卡住WinForm主线程,导致窗口无响应;上述Timer方案为异步等待,不会占用UI线程资源
  • Alarm.exe建议填写完整的绝对路径(例如@"D:\Tools\Alarm.exe"),避免程序在不同工作目录下启动时找不到目标文件
  • 组件初始化时务必将timer1的Enabled属性设为false,否则会跳过8小时前置等待直接触发判断流程

内容的提问来源于stack exchange,提问作者Dunno123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.04 12:06:05