官网:https://www.quartz-scheduler.net/
添加依赖
<PackageReference Include="Quartz.AspNetCore" Version="3.5.0" />
创建一个任务类
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
//ConsoleUtil.WriteLine("Greetings from HelloJob!");
// Console.WriteLine(666);
}
}
在program中注册
serviceCollection.AddQuartz(q =>
{
// handy when part of cluster or you want to otherwise identify multiple schedulers
q.SchedulerId = "Scheduler-Core";
// we take this from appsettings.json, just show it's possible
// q.SchedulerName = "Quartz ASP.NET Core Sample Scheduler";
// as of 3.3.2 this also injects scoped services (like EF DbContext) without problems
q.UseMicrosoftDependencyInjectionJobFactory();
// or for scoped service support like EF Core DbContext
// q.UseMicrosoftDependencyInjectionScopedJobFactory();
q.UseDefaultThreadPool(tp => { tp.MaxConcurrency = 10; });
// quickest way to create a job with single trigger is to use ScheduleJob
// (requires version 3.2)
q.ScheduleJob<HelloJob>(trigger => trigger
//.WithIdentity("trigger3", "group1")
// 5s一次
.WithCronSchedule("0/5 * * * * ? ")
);
});
// ASP.NET Core hosting
serviceCollection.AddQuartzServer(options =>
{
// when shutting down we want jobs to complete gracefully
options.WaitForJobsToComplete = true;
});