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();
    }
}
相关推荐
hez201016 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间3 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
sali-tec3 天前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#