using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading;
namespace RobotManagementWeb.Jobs
{
public class JobExcuter : BackgroundService
{
private readonly ILogger<JobExcuter> _logger;
public JobExcuter(ILogger<JobExcuter> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await new TaskFactory().StartNew(() =>
{
try
{
//满足某种条件执行 比如每天凌晨执行
var time = DateTime.Now.ToString("HH:mm:ss");
if ("06:00:00" == time)
{
JobDatabase.JobChatInfoShrink();
_logger.LogError("定时删除:成功");
}
}
catch (Exception e)
{
_logger.LogError("定时删除异常:失败-" + e.Message);
}
//定时任务休眠
Thread.Sleep(1 * 1000);
});
}
}
}
}
然后 需要在我们可以在做一个静态方法,用来定制执行,如果需要使用数据库的话,请仿照下面的方式
using System;
using System.Linq;
using DAL;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace RobotManagementWeb.Jobs
{
public class JobDatabase
{
public static IConfiguration Configuration { get; set; }
//private readonly flowDataContext _flowcontext;
public static void JobChatInfoShrink()
{
//配置configaration
var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables();
Configuration = builder.Build();
//获取数据库上下文
var flowconnectionString = Configuration.GetConnectionString("FlowConnection");
Microsoft.EntityFrameworkCore.DbContextOptionsBuilder<flowDataContext> option = new Microsoft.EntityFrameworkCore.DbContextOptionsBuilder<flowDataContext>();
MySqlDbContextOptionsExtensions.UseMySql(option, flowconnectionString);
var _flowcontext= new flowDataContext(option.Options);
//这里就可以随意使用上下文来操作数据库
}
}
}
最后在startup.cs中的ConfigureServices里注册下
//定时任务的注入
//services.AddTransient<Microsoft.Extensions.Hosting.IHostedService, Job>();