Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 每天定时执行操作

作者:狂暴的酷   发布日期:2026-06-24   浏览:109

using System;
using System.Timers;

class Program
{
    static Timer timer;

    static void Main(string[] args)
    {
        // 设置定时器,每天的特定时间执行操作
        timer = new Timer();
        timer.Interval = CalculateIntervalToNextExecutionTime(new TimeSpan(14, 0, 0)); // 每天14:00执行
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true;
        timer.Enabled = true;

        Console.WriteLine("等待定时任务触发...");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("定时任务执行于: " + DateTime.Now);
        // 在这里编写你想要定时执行的操作代码
        // 例如:调用方法、发送邮件等
    }

    private static double CalculateIntervalToNextExecutionTime(TimeSpan executionTime)
    {
        DateTime now = DateTime.Now;
        DateTime todayExecution = now.Date + executionTime;
        if (now >= todayExecution)
        {
            todayExecution = todayExecution.AddDays(1);
        }
        return (todayExecution - now).TotalMilliseconds;
    }
}

解释说明:

  1. Timer 类:使用 System.Timers.Timer 类来创建一个定时器。定时器会在指定的时间间隔后触发事件。
  2. CalculateIntervalToNextExecutionTime 方法:计算从当前时间到下一次执行时间(例如每天的14:00)之间的毫秒数。
  3. OnTimedEvent 方法:这是定时器触发时调用的方法,在这里可以编写你想要定时执行的具体操作。
  4. AutoReset 属性:设置为 true,表示定时器会在每次触发后自动重置,以便每天同一时间再次触发。
  5. Enabled 属性:启用定时器。

通过这种方式,你可以实现每天在指定时间执行某些操作。

上一篇:c# 等待多少秒写法

下一篇:c# 写文本文件

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站