c# 实现每个整数分钟执行一次的定时任务

StartAsync 方法中,计算了下一个整数分钟的时间,然后使用 System.Threading.Timer 类创建定时器,并将首次触发时间设为该时间。在 InsertDB2Async 方法中,我们定义了要执行的操作,然后使用 await Task.Delay(1000) 模拟异步操作的等待时间。最后,我们重新计算下一个整数分钟的时间,并使用 Change 方法设置定时器的下一次触发时间。

需要注意的是,InsertDB2Async 方法是异步方法,但是我们使用的是 async void 定义方法。在实际应用中,应该使用 async Task 定义异步方法,以避免出现无法捕获的异常。另外,System.Threading.Timer 类的回调方法是在另一个线程上执行的,因此在操作期间需要注意线程安全。

cs 复制代码
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

public class MyTimerHostedService : IHostedService, IDisposable
{
    private Timer _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        // 计算下一个整分钟的时间,并设置定时器的首次触发时间
        var now = DateTime.Now;
        var nextMinute = now.AddMinutes(1);
        var target = nextMinute.AddSeconds(-nextMinute.Second);
        var delay = (int)(target - now).TotalMilliseconds;
        _timer = new Timer(InsertDB2Async, null, delay, 60000);
        return Task.CompletedTask;
    }

    private async void InsertDB2Async(object state)
    {
        try
        {
            // 在这里写你要执行的代码
            Console.WriteLine($"[{DateTime.Now}] Hello, world!");
            // 等待异步操作完成
            await Task.Delay(1000);
        }
        finally
        {
            // 计算下一个整分钟的时间,并设置定时器的下一次触发时间
            var now = DateTime.Now;
            var nextMinute = now.AddMinutes(1);
            var target = nextMinute.AddSeconds(-nextMinute.Second);
            var delay = (int)(target - now).TotalMilliseconds;
            _timer.Change(delay, 60000);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer.Dispose();
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer.Dispose();
    }
}
相关推荐
冰茶_8 小时前
WPF之TextBox控件详解
学习·microsoft·微软·c#·wpf
大飞pkz12 小时前
【Unity】使用XML进行数据读存的简单例子
xml·unity·c#·游戏引擎·游戏开发·数据读写
编程乐趣16 小时前
基于C#开发的适合Windows开源文件管理器
开发语言·windows·c#
code_shenbing19 小时前
C# 实现列式存储数据
开发语言·c#·存储
code_shenbing19 小时前
.NET Core 数据库ORM框架用法简述
数据库·c#·.netcore·orm
ghost14321 小时前
C#学习第20天:垃圾回收
开发语言·学习·c#
code_shenbing1 天前
WPF实现类似Microsoft Visual Studio2022界面效果及动态生成界面技术
ui·c#·wpf·上位机
code_shenbing1 天前
C# 高效操作excel文件
c#·excel·图表
code_shenbing1 天前
C#扩展方法与Lambda表达式基本用法
开发语言·c#·lambda表达式·扩展方法
FAREWELL000751 天前
C#进阶学习(十七)PriorityQueue<TElement, TPriority>优先级队列的介绍
开发语言·学习·c#·优先级队列