在ASP .NET Core 2.1中实现Cronjob的解决方法如下:
Microsoft.Extensions.Hosting
Quartz.Extensions.Hosting
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddHostedService();
// ...
}
}
using System;
using System.Threading.Tasks;
using Quartz;
public class SampleJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
// 执行定时任务的逻辑代码
await Task.Run(() =>
{
Console.WriteLine("Job executed at: " + DateTime.Now);
});
}
}
using Quartz;
using Quartz.Spi;
public class JobFactory : IJobFactory
{
private readonly IServiceProvider _serviceProvider;
public JobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
var jobDetail = bundle.JobDetail;
return (IJob)_serviceProvider.GetService(jobDetail.JobType);
}
public void ReturnJob(IJob job) { }
}
using System;
using System.Threading.Tasks;
using Quartz;
public class JobScheduler
{
private readonly ISchedulerFactory _schedulerFactory;
private readonly IScheduler _scheduler;
public JobScheduler(ISchedulerFactory schedulerFactory)
{
_schedulerFactory = schedulerFactory;
_scheduler = _schedulerFactory.GetScheduler().GetAwaiter().GetResult();
}
public async Task StartAsync()
{
await _scheduler.Start();
var job = JobBuilder.Create()
.WithIdentity("sample-job", "sample-group")
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity("sample-trigger", "sample-group")
.StartNow()
.WithCronSchedule("0/5 * * * * ?") // 设置Cron表达式,每5秒执行一次
.Build();
await _scheduler.ScheduleJob(job, trigger);
}
public async Task StopAsync()
{
await _scheduler.Shutdown();
}
}
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
public class QuartzHostedService : IHostedService
{
private readonly JobScheduler _jobScheduler;
public QuartzHostedService(JobScheduler jobScheduler)
{
_jobScheduler = jobScheduler;
}
public Task StartAsync(CancellationToken cancellationToken)
{
return _jobScheduler.StartAsync();
}
public Task StopAsync(CancellationToken cancellationToken)
{
return _jobScheduler.StopAsync();
}
}
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
以上代码实现了在ASP .NET Core 2.1中使用Quartz实现Cronjob。在示例代码中,定时任务每5秒执行一次,可以根据需求修改Cron表达式。