C#实现定时执行任务

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

class Program
{
    static void Main()
    {
        Timer timer = new Timer();
        timer.Interval = 1000; // 设置定时器间隔时间,单位为毫秒
        timer.Elapsed += Timer_Elapsed;
        timer.Start();

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }

    private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine($"Task executed at {DateTime.Now}");
    }
}

在上面的代码中,首先创建了一个Timer实例,设置了定时器的间隔时间为1秒,并添加了一个Elapsed事件处理程序。在Elapsed事件处理程序中,输出当前时间,表示定时执行的任务。

运行程序后,定时器将每隔1秒执行一次任务,直到按下任意键退出程序。

相关推荐
ascarl201038 分钟前
准确--k8s cgroup问题排查
java·开发语言
dancing9991 小时前
cocos3.X的oops框架oops-plugin-excel-to-json改进兼容多表单导出功能
前端·javascript·typescript·游戏程序
fpcc1 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗2 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长2 小时前
Python 构建法律DeepSeek RAG
开发语言·python
萌萌哒草头将军2 小时前
🚀🚀🚀Prisma 发布无 Rust 引擎预览版,安装和使用更轻量;支持任何 ORM 连接引擎;支持自动备份...
前端·javascript·vue.js
luojiaao2 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码2 小时前
STL解析——list的使用
开发语言·c++
SoFlu软件机器人2 小时前
智能生成完整 Java 后端架构,告别手动编写 ControllerServiceDao
java·开发语言·架构
书语时2 小时前
ES6 Promise 状态机
前端·javascript·es6