C# 设置一个定时器函数

C#中,创建设置一个定时器,能够定时中断执行特定操作,可以用于发送心跳、正计时和倒计时等。

本文对C#的定时器简单封装一下,哎,以方便定时器的创建。

定义

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

class SetTimer
{
    Timer aTimer = null;

    /// <summary>
    /// 设置定时器函数
    /// </summary>
    public delegate void TimerWork(object source, ElapsedEventArgs e);

    /// <summary>
    /// 每隔 interval/1000 秒 发送控制器心跳信号
    /// </summary>
    /// <param name="interval">时间间隔,单位是毫秒</param>
	/// <param name="work">定义的需要触发的函数</param>
    public SetTimer(int interval, TimerWork work)
    {
        // 创建一个定时器
        aTimer = new Timer(interval);

        // 绑定触发事件.
        aTimer.Elapsed += new System.Timers.ElapsedEventHandler(work);

        aTimer.AutoReset = true;    // 让计时器触发重复事件(true是默认值)
        aTimer.Enabled = true;      // 启动 timer,与aTimer.Start()同
    }
    /// <summary>
    /// 停止计时
    /// </summary>
    public void Stop()
    {
        if (aTimer != null)
        {
            aTimer.Enabled = false; // 停止计时
            aTimer.Dispose();       // 释放资源
            aTimer = null;          // 设为空值
        }
    }
}

应用

csharp 复制代码
static void Main(string[] args)
{
    int second = 0;
    // 此处也可以定义一个对象名,然后在某时刻关闭它。
    new SetTimer(1000, (source, e) =>
    {
        Console.Write(second++);
    });
}
相关推荐
夜莺悠吟41 分钟前
关于对 C# 中 ImplicitUsings,GlobalUsings 的讨论
c#·.net
-银雾鸢尾-7 小时前
C#中的拓展方法
开发语言·c#
EIP低代码平台20 小时前
EIP低代码平台-系统参数配置详解|落地三级等保+高灵活私有化部署方案
低代码·c#·权限·工作流·netcore
王莎莎-MinerU21 小时前
MCP 解决的是工具接入,科研 Agent 还缺的是科学证据接口标准化
开发语言·网络·人工智能·深度学习·pdf·c#·php
-银雾鸢尾-21 小时前
C#中Object类内的方法
开发语言·c#
tiankong12131 天前
如何拓展多态下的子类
设计模式·c#
geats人山人海1 天前
c# 第九章 record
开发语言·c#
-银雾鸢尾-1 天前
C#中的抽象类与抽象方法
开发语言·c#
影寂ldy1 天前
C# Task 进阶:WaitAll / WaitAny / WhenAll / WhenAny
开发语言·c#