【C#】C#中System.Timers.Timer定时触发事件的计时器类,运用

System.Timers.Timer 类用于创建定时器,它可以在指定的时间间隔内触发事件。

创建 Timer 实例: 使用 new System.Timers.Timer() 创建一个新的定时器实例。

设置定时器属性: 设置定时器的属性,主要包括 Interval(触发事件的时间间隔)和 AutoReset(指定是否重复触发事件)。

订阅 Elapsed 事件: 使用 Elapsed 事件来定义在时间间隔到达时执行的操作。

启动定时器: 调用 Start 方法启动定时器。

停止定时器(如果需要): 可以使用 Stop 方法停止定时器。

csharp 复制代码
using System;
using System.Timers;

class Program
{
    private static System.Timers.Timer myTimer;

    static void Main()
    {
        // 创建定时器实例
        myTimer = new System.Timers.Timer();

        // 设置触发事件的时间间隔为 1秒 
        myTimer.Interval = 1000;

        // 设置 AutoReset 为 true,使定时器在每个时间间隔到达时重置并触发 Elapsed 事件
        myTimer.AutoReset = true;//当 AutoReset 设置为 false 时,计时器只会在第一次触发 Elapsed 事件后停止,除非手动调用 Start 方法重新启动计时器。AutoReset 属性的默认值是 true

        // 指定 Elapsed 事件的处理方法
        myTimer.Elapsed += OnTimerElapsed;

        // 启动定时器
        myTimer.Start();

        Console.WriteLine("Press Enter to stop the timer.");
        Console.ReadLine();  // 阻塞主线程等待用户输入

        // 停止定时器
        myTimer.Stop();
        Console.WriteLine("Timer stopped. Press Enter to exit.");
        Console.ReadLine();
    }

    // Elapsed 事件的处理方法
    private static void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Timer elapsed! Performing some task...");

        // 在这里可以添加定时器触发时要执行的操作

        Console.WriteLine("Task completed.");
    }
}
相关推荐
齐鲁大虾18 小时前
新人编程语言选择指南
javascript·c++·python·c#
加号318 小时前
【C#】 WebAPI 接口设计与实现指南
开发语言·c#
unicrom_深圳市由你创科技19 小时前
上位机开发常用的语言 / 框架有哪些?
c++·python·c#
xiaoshuaishuai821 小时前
C# ZLibrary数字资源分发
开发语言·windows·c#
Eiceblue1 天前
C# 实现 XLS 与 XLSX 格式双向互转(无需依赖 Office)
开发语言·c#·visual studio
aini_lovee1 天前
基于C#的三菱PLC串口通信实现方案
服务器·网络·c#
光泽雨1 天前
c#MVVM中的消息通知机制
服务器·c#
江沉晚呤时1 天前
C# 整型溢出处理机制:checked 与 unchecked 上下文解析
c#·.net
yngsqq1 天前
Vlookup用法
c#
bitt TRES1 天前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互