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

C#常用的定时任务几种方式

admin
2025年6月16日 23:53 本文热度 96

一、System.Threading.Timer

1秒后首次触发,之后每2秒触发一次

using System.Threading;
class Program{    static void Main()    {        // 创建定时器(回调函数,状态对象,初始延迟,间隔)        var timer = new Timer(            callback: state => Console.WriteLine($"触发时间: {DateTime.Now:T}"),            state: null,            dueTime: 1000,    // 1秒后首次触发            period: 2000       // 之后每2秒触发一次        );
        Console.ReadLine();        timer.Dispose(); // 释放资源    }}

轻量级,基于线程池,适合高性能后台任务。

无事件机制,通过回调函数触发。

手动控制 启动/停止(通过 Change 方法)。

不直接支持 UI 操作(需手动切换线程)。

二、 System.Timers.Timer

间隔1秒执行一次

using System.Timers;
class Program{    static void Main()    {        var timer = new System.Timers.Timer(interval: 1000); // 1秒间隔        timer.Elapsed += (sender, e) => Console.WriteLine($"触发时间: {e.SignalTime:T}");        timer.AutoReset = true// 是否循环触发        timer.Start();
        Console.ReadLine();        timer.Stop();    }}

每天23点59分59秒执行一次任务

using System.Timers;
class DailyTask{        static Timer timer;        static void Main() { SetTimer(); Console.WriteLine("定时服务已启动..."); }
       static void SetTimer() {          var now = DateTime.Now;          var target = new DateTime(now.Year, now.Month, now.Day, 235959);          if (now > target) target = target.AddDays(1);
timer = new Timer((target - now).TotalMilliseconds); timer.Elapsed += (s,e) => {//执行你的任务代码 Console.WriteLine($"{DateTime.Now} 执行每日任务");
//下一次执行时间 timer.Interval = TimeSpan.FromDays(1).TotalMilliseconds; }; timer.Start(); }}

基于事件(Elapsed 事件),代码更易读。

支持自动重置(AutoReset 属性控制是否循环)。

可绑定到 UI 线程(通过 SynchronizingObject,仅 WinForms)。

适合需要事件机制的场景(如 UI 定时更新)。

三、using System.Windows.Threading

using System.Windows.Threading;
public partial class MainWindow : Window {    private DispatcherTimer _timer;    public MainWindow() {        InitializeComponent();        _timer = new DispatcherTimer();        _timer.Interval = TimeSpan.FromSeconds(1);        _timer.Tick += (s, e) => lblTime.Content = DateTime.Now.ToString("HH:mm:ss");        _timer.Start();    }}

DispatcherTimer必须在UI线程创建

默认Interval为1秒更新

MVVM模式需实现INotifyPropertyChanged接口

两种实现方式各有适用场景,MVVM更适合复杂业务

注意避免直接在其他线程修改UI元素,这是选择DispatcherTimer而非System.Timers.Timer的主要原因。如需动态调整间隔时间,可通过修改Interval属性实现

四、using System.Threading.Tasks;

using System.Threading.Tasks;
public void UploadTimer(){ Task.Run(async () => {while (IsTurnOnOk) {try {//执行任务 Test();
//间隔5秒await Task.Delay(5000); }catch (Exception ex) { } } });}

支持 async/await 语法糖

提供任务取消(CancellationToken)

支持任务延续(ContinueWith)

并行任务处理(Task.WhenAll/WhenAny)

‌与DispatcherTimer的区别‌:

Tasks 是通用的异步编程模型

DispatcherTimer 专为UI线程定时器设计

Tasks 不自动关联UI线程上下文


阅读原文:原文链接


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