LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C# 实现定时任务的5种原生方法

admin
2025年6月2日 10:47 本文热度 386

前言

程序猿小张最近遇到了一个难题——他需要每天早上9点自动给老板发送工作报告,就像个数字化的公鸡打鸣一样准时。在C#的世界里,这样的定时任务该怎么实现呢?

定时器在编程中就像你的私人助理,可以帮你按时执行各种任务:数据备份、邮件发送、缓存清理...

今天,就让我们一起来探索C#中那些让你成为 "时间管理大师" 的定时器吧!

1. System.Timers.Timer

System.Timers.Timer 就像一个全能型选手,它是基于服务器的定时器,精度较高,适合需要在特定时间间隔重复执行的任务,特别要说明的是,它是线程安全的。

using System;
using System.Timers;

classProgram
{
    static void Main()
    {
        var timer = new System.Timers.Timer(1000); // 1秒间隔
        timer.Elapsed += (sender, e) => 
        {
            Console.WriteLine($"定时任务执行啦!时间:{e.SignalTime}");
        };
        timer.AutoReset = true// 设置为重复触发
        timer.Start();
        
        Console.WriteLine("按任意键退出...");
        Console.ReadKey();
        timer.Stop();
    }
}

2. System.Threading.Timer

System.Threading.Timer 是一个轻量级的定时器,它性能更好,没有UI组件依赖,适合后台任务,不过在使用时,一定要记得手动释放资源。

using System;
using System.Threading;

classProgram
{
    static void Main()
    {
        // 参数:回调方法, 状态对象, 延迟时间, 间隔时间
        var timer = new Timer(state => 
        {
            Console.WriteLine($"线程定时器触发!时间:{DateTime.Now}");
        }, null10002000); // 1秒后开始,每2秒触发
        
        Console.WriteLine("按任意键退出...");
        Console.ReadKey();
        timer.Dispose(); // 记得释放资源
    }
}

3. System.Windows.Forms.Timer

这是一个专为 Windows Forms 设计的定时器,事件在 UI 线程上触发,可以直接操作 UI 控件,非常适合用于更新用户界面元素,不过,它的精度较低(约55ms),不太适合高精度定时。

using System;
using System.Windows.Forms;

classProgram
{
    static void Main()
    {
        var form = new Form();
        var timer = new Timer { Interval = 1000 }; // 1秒间隔
        
        timer.Tick += (sender, e) =>
        {
            Console.WriteLine($"窗体定时器触发!时间:{DateTime.Now}");
        };
        
        timer.Start();
        Application.Run(form);
    }
}

4. Stopwatch

Stopwatch 通常用来测量程序的执行时间,它的精度非常高,达到微秒级,所以换一个思路,也可以把它作为定时器,比如下面这个例子:

using System;
using System.Diagnostics;
using System.Threading;

classProgram
{
    static void Main()
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        
        while (true)
        {
            if (stopwatch.ElapsedMilliseconds >= 1000)
            {
                Console.WriteLine($"高精度计时!时间:{DateTime.Now}");
                stopwatch.Restart();
            }
            Thread.Sleep(10); // 降低CPU占用
        }
    }
}

5. Thread.Sleep 和 Task.Delay

有时候,我们只需要简单的延迟执行某些代码,这时候可以使用 Thread.Sleep(同步)或 Task.Delay(异步) 来实现,如:

using System;
using System.Threading.Tasks;

public class AsyncAwaitExample
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine("开始计时...");
        await Task.Delay(5000); // 等待5秒
        Console.WriteLine("5秒后...");
    }
}

总结

现在你已经掌握了 C# 定时器的“十八般武艺”,是时候做个总结了!

  • 简单任务:System.Threading.Timer/Task.Delay(Thread.Sleep)
  • 简单任务且高精度:Stopwatch
  • UI相关:Windows.Forms.Timer
  • 服务器应用:System.Timers.Timer

现在,去用代码驯服时间吧!


该文章在 2025/6/2 12:49:18 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved