我正在尝试在net net应用程序中使用quartz.net 3.0创建触发器并开始工作。 这是一个代码: mycontroller.cs
public async Task<IActionResult> CreateHomeWorkReminder([FromBody] CreateHomeWorkReminderRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_logger.LogInformation("data valid");
var dict = new Dictionary<string, object> { {nameof(CreateHomeWorkReminderRequest.UserId), request.UserId },
{nameof(CreateHomeWorkReminderRequest.HomeWorkId), request.HomeWorkId}};
await _registerJob.CreateJob<ReminderJob>(nameof(CreateHomeWorkReminder), dict, request.DateOfReminder);
_logger.LogInformation("saving ok");
return Ok(result.Result);
}
RegisterJob.cs(mycontroller.cs中的contructor中的DI):
public class RegisterJob : IRegisterJob
{
ISchedulerBot bot;
public async Task CreateJob<T>(string jobName, IDictionary<string, object> map, DateTime dateOfReminder) where T : IJob
{
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
// get a scheduler
IScheduler sched = await factory.GetScheduler();
await sched.Start();
var job = JobBuilder.Create<ReminderJob>().Build();
var trigger = TriggerBuilder.Create().StartNow().Build();
await sched.ScheduleJob(job, trigger);
}
}
}
和ReminderJob.cs
public class ReminderJob : IJob
{
ILogger<ReminderJob> logger;
public ReminderJob(ILogger<ReminderJob> _logger)
{
logger = _logger;
}
public Task Execute(IJobExecutionContext context)
{
var parameters = context.JobDetail.JobDataMap;
var userId = parameters.GetLongValue("UserId");
var homeWorkId = parameters.GetLongValue("HomeWorkId");
logger.LogInformation($"userId = {userId}, homeWorkId = {homeWorkId}");
return Task.FromResult(0);
}
}
我正在尝试调试代码,但从未尝试过ReminderJob.cs的Execute方法。我的错误在哪里?我应该执行什么工作?谢谢您的关注。
答案 0 :(得分:0)
正确的答案:在Quartz 3.0中不能使用DI。我用ILogger的DI删除了ReminderJob中的构造函数,并且代码起作用了。
public class ReminderJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
var parameters = context.JobDetail.JobDataMap;
var userId = parameters.GetLongValue("UserId");
var homeWorkId = parameters.GetLongValue("HomeWorkId");
await System.Console.Out.WriteLineAsync("HelloJob is executing.");
}