如何在后台的计时器上写入数据库。例如,检查邮件并将新字母添加到数据库。在示例中,我在写入数据库之前简化了代码。
Microsoft示例中的类名称。录音课本身:
namespace EmailNews.Services
{
internal interface IScopedProcessingService
{
void DoWork();
}
internal class ScopedProcessingService : IScopedProcessingService
{
private readonly ApplicationDbContext _context;
public ScopedProcessingService(ApplicationDbContext context)
{
_context = context;
}
public void DoWork()
{
Mail mail = new Mail();
mail.Date = DateTime.Now;
mail.Note = "lala";
mail.Tema = "lala";
mail.Email = "lala";
_context.Add(mail);
_context.SaveChangesAsync();
}
}
}
Run Code Online (Sandbox Code Playgroud)
计时器类:
namespace EmailNews.Services
{
#region snippet1
internal class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public TimedHostedService(IServiceProvider services, ILogger<TimedHostedService> …Run Code Online (Sandbox Code Playgroud) c# async-await asp.net-core asp.net-core-2.1 asp.net-core-hosted-services