.Net6实现定时任务

发布时间 2023-07-28 11:58:55作者: 不见离愁

首先创建一个类Background

实现代码:

using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartMedicalCare.Web
{
public class Background : IHostedService, IDisposable
{
private Timer? timer;

private void DoWork(object state)
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
}
public void Dispose()
{
timer?.Dispose();
}
/// <summary>
/// Triggered when the application host is ready to start the service.
/// </summary>
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
public Task StartAsync(CancellationToken cancellationToken)
{
timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;

}

public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("StopAsync");
return Task.CompletedTask;

}

}
}

 

然后在Program中加入以下代码:

//注册定时任务
builder.Services.AddHostedService<Background>();

如果有Autofac的话前把代码写在AutoFac上面

 

以上代码实现的是每隔5秒输出当前时间

效果图: