.net core 提供了抽象类BackgroundService,所以并不需要自己构造
因为Task没有方法支持在外部取消Task,只能通过一个公共变量存放线程的取消状态,在线程内部通过变量判断线程是否被取消,当CancellationToken是取消状态,Task内部未启动的任务不会启动新线程。所以需要取消令牌(CancellationToken)
namespace RepairServices.Service
{
public class HostedService : BackgroundService
{
protected async override Task ExecuteAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
await new TaskFactory().StartNew(() =>
{
try
{
//满足某种条件执行 比如每天凌晨执行
var time = DateTime.Now.ToString("HH");
if ("09" == time)
{
SendWarn();
}
}
catch (Exception e)
{
}
//定时任务休眠
Thread.Sleep(1 * 600000);
});
}
}
//倒计时事件
public void SendWarn()
{
List<string> PhoneList = CheckPhone();
for(int i = 0; i < PhoneList.Count; i++)
{
string phone = PhoneList[i];
var sendSms = new SendSmsMessage();
sendSms.SendCreateOrderMessage(phone);
}
}
private readonly IReviewRepository _ReviewRepository;
public HostedService(IReviewRepository ReviewRepository)
{
_ReviewRepository = ReviewRepository;
}
public List<string> CheckPhone()
{
List<string> PhoneList = new List<string>();
var date = DateTime.Now.ToString("yyyy-MM-dd");
DateTime checkDate = Convert.ToDateTime(date).AddDays(-8);
//获取维修员名单
string role = "repair-token";
List<string> User = _ReviewRepository.CheckUser(role);
for (int i = 0; i < User.Count; i++)
{
string UserId = User[i];
List<CallList> List= _ReviewRepository.CheckTime(UserId);
if (List.Count != 0)
{
DateTime Time = List[0].Time;
if (Time == checkDate)
{
string user = List[0].UserId;
string phone = _ReviewRepository.CheckPhone(user);
PhoneList.Add(phone);
}
}
}
return PhoneList;
}
}
}
之后记得在Startup.cs里注入到ServiceCollection 中
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<HostedService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}