我添加了一个Timer
到Startup
类的的ASP.Net Core
应用。它会在某个时间段触发,并执行诸如记录示例文本的操作。我需要它能够执行数据库驱动的操作,例如将记录添加到表中。因此,我尝试AppDbContext
从DI 获取信息,但它始终为null。请查看代码:
public class Scheduler
{
static Timer _timer;
static bool _isStarted;
static ILogger<Scheduler> _logger;
const int dueTimeMin = 1;
const int periodMin = 1;
public static void Start(IServiceProvider serviceProvider)
{
if (_isStarted)
throw new Exception("Currently is started");
_logger = (ILogger<Scheduler>)serviceProvider.GetService(typeof(ILogger<Scheduler>));
var autoEvent = new AutoResetEvent(false);
var operationClass = new OperationClass(serviceProvider);
_timer = new Timer(operationClass.DoOperation, autoEvent, dueTimeMin * 60 * 1000, periodMin * 60 * 1000);
_isStarted = true;
_logger.LogInformation("Scheduler started"); …
Run Code Online (Sandbox Code Playgroud)