FIC_Solar/SolarPower/Services/Implement/SendEmailBackgroundService.cs
Kai 18e4fa4b57 1. 加入Quartz
2. 地圖總覽
2021-07-01 09:51:33 +08:00

69 lines
1.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SolarPower.Services.Implement
{
public class SendEmailBackgroundService : IHostedService, IDisposable
{
static Timer _timer;
private int time_interval = 30; //查詢間隔(秒)
private readonly ILogger<SendEmailBackgroundService> _log;
private int execCount = 0;
public SendEmailBackgroundService(ILogger<SendEmailBackgroundService> log)
{
this._log = log;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(DoWork, null,
TimeSpan.Zero,
TimeSpan.FromSeconds(time_interval));
return Task.CompletedTask;
}
public void DoWork(object state)
{
//利用 Interlocked 計數防止重複執行
if (execCount <= 0)
{
Interlocked.Increment(ref execCount);
}
if (execCount == 1)
{
try
{
}
catch (Exception ex)
{
}
finally
{
Interlocked.Decrement(ref execCount);
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
//調整Timer為永不觸發停用定期排程
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
throw new NotImplementedException();
}
}
}