【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.");
    }
}
相关推荐
xiaowu08010 小时前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful12 小时前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide12 小时前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
gc_229914 小时前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty2717 小时前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
c#上位机21 小时前
wpf之TextBlock
c#·wpf
almighty271 天前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
almighty271 天前
C#实现导入CSV数据到List<T>的完整教程
c#·csv·格式转换·c#导入数据·csv数据导入
程序猿多布1 天前
Lua和C#比较
c#·lua
csdn_aspnet2 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore