using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace Dpz.Core.Infrastructure
{
public sealed class TimedHostedService : IHostedService, IDisposable
{
private int executionCount = 0;
private Timer _timer;
private readonly Random _random = new Random();
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(async x => await DoWorkAsync(x), null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
return Task.CompletedTask;
}
public async Task DoWorkAsync(object state)
{
if (executionCount >= 10)
{
_timer?.Change(Timeout.Infinite, 0);
return;
}
var sleepTime = _random.Next(10, 61);
Thread.Sleep(sleepTime * 1000);
executionCount++;
await File.AppendAllTextAsync(@"D:/doWork.txt",
$"time:{DateTime.Now:yyyy-MM-dd HH:mm:ss} count:{executionCount} random:{sleepTime} ThreadId:{Thread.GetCurrentProcessorId()}\r\n",
Encoding.UTF8);
}
public Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
}