基于 System.Timers.Timer 实现定时执行任务,支持重复执行和单次执行。
using System.Timers; public class ScheduledTask { private readonly Timer _timer; private readonly Action _taskAction; private bool _isSingleShot; // 构造函数:初始化定时任务 public ScheduledTask(double intervalMs, Action task, bool isSingleShot = false) { _timer = new Timer(intervalMs); _taskAction = task; _isSingleShot = isSingleShot; _timer.Elapsed += OnTimerElapsed; _timer.AutoReset = !isSingleShot; } private void OnTimerElapsed(object sender, ElapsedEventArgs e) { try { Console.WriteLine($"任务执行时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); _taskAction.Invoke(); if (_isSingleShot) { Stop(); } } catch (Exception ex) { Console.WriteLine($"任务执行失败: {ex.Message}"); } } // 启动任务 public void Start() { _timer.Start(); Console.WriteLine("定时任务已启动"); } // 停止任务 public void Stop() { _timer.Stop(); Console.WriteLine("定时任务已停止"); } // 调用示例 public static void TestTask() { // 每5秒执行一次打印任务 var task = new ScheduledTask(5000, () => { Console.WriteLine("这是定时执行的任务内容"); }); task.Start(); // 按任意键停止 Console.ReadKey(); task.Stop(); } }