program添加服务
// .Net 6 builder.Services.AddHostedService<TestHostedService>(); // .Net 5 及以下 services.AddHostedService<TestHostedService>();
- 添加工作类
public class TestHostedService : IHostedService, IDisposable { private Timer? _timer; /// <summary> /// 任务开始 /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public Task StartAsync(CancellationToken cancellationToken) { _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); return Task.CompletedTask; } private void DoWork(object? state) { Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"); } /// <summary> /// 任务停止 /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public Task StopAsync(CancellationToken cancellationToken) { Console.WriteLine("StopAsync"); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } }
- 效果
标签:Core,Task,cancellationToken,timer,public,后台任务,IHostedService,NET From: https://www.cnblogs.com/Echoxxx/p/17174500.html