一、搭建
1—命令行项目
从网络搜了好几个博文,测试其中一个。通过nuget 搜索并安装Quartz
2—编写任务job
这里通过添加2个定时任务
internal class timejob : IJob
{
Task IJob.Execute(IJobExecutionContext context)
{
return Task.Run(() =>
{
var wtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string path = "/demo.log";
using (StreamWriter sw=new StreamWriter(path,true))
{
sw.WriteLine("执行作业 "+wtime);
}
});
}
}
internal class timejob2 : IJob
{
Task IJob.Execute(IJobExecutionContext context)
{
return Task.Run(() =>
{
var wtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string path = "/demo.log";
using (StreamWriter sw = new StreamWriter(path, true))
{
sw.WriteLine("执行作业2 " + wtime);
}
});
}
}
3—设定触发器和任务调度
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始作业");
IScheduler scheduler;
ISchedulerFactory factory = new StdSchedulerFactory();
scheduler = factory.GetScheduler().Result;
IJobDetail testJob = JobBuilder.Create<timejob>().WithIdentity("timejob").Build();
ITrigger jobTrigger = TriggerBuilder.Create().WithCronSchedule("0/5 * * * * ? *").Build();
IJobDetail secJob = JobBuilder.Create<timejob2>().WithIdentity("timejob2").Build();
ITrigger secTrigger = TriggerBuilder.Create().WithCronSchedule("0/10 * * * * ? *").Build();
//动态添加第1个任务,5秒执行一次
scheduler.ScheduleJob(testJob, jobTrigger);
//添加第2个任务 10秒执行一次
scheduler.ScheduleJob(secJob,secTrigger);
scheduler.Start();
while (true)
{
}
}
}
二、添加到web项目
1—构建
与一段落相同
2—工作任务
声明了2个任务类
public class SyncJob : IJob
{
async Task IJob.Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync($"{DateTime.Now:HH:mm:ss}--数据同步完成!");
}
}
public class SyncJob2 : IJob
{
async Task IJob.Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync($"{DateTime.Now:HH:mm:ss}---------数据synchroize完成!");
}
}
3—任务工厂类
public class SyncJobFactory : IJobFactory
{
private readonly IServiceProvider _serviceProvider;
public SyncJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider?? throw new ArgumentNullException(nameof(serviceProvider));
}
IJob IJobFactory.NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return _serviceProvider.GetRequiredService(bundle.JobDetail.JobType) as IJob;
}
void IJobFactory.ReturnJob(IJob job)
{
//throw new System.NotImplementedException();
}
}
4—任务调度中心
public class SchedulerCenter
{
private readonly IJobFactory _jobFactory;
private readonly ISchedulerFactory _schedulerFactory;
private IScheduler _scheduler;
public SchedulerCenter(IJobFactory jobFactory, ISchedulerFactory schedulerFactory)
{
_jobFactory = jobFactory;
_schedulerFactory = schedulerFactory;
}
public async void StartScheduler()
{
_scheduler=await _schedulerFactory.GetScheduler();
//替换默认工厂
_scheduler.JobFactory = this._jobFactory;
IJobDetail job = JobBuilder.Create<SyncJob>()
.WithIdentity("SyncJob","SyncJobGroup").Build();
//配置触发条件
ITrigger trigger = TriggerBuilder.Create()
.WithCronSchedule("0/5 * * * * ? *")
.WithIdentity("SyncJob", "SyncJobGroup").Build();
//配置第2个定时任务
IJobDetail job2=JobBuilder.Create<SyncJob2>()
.WithIdentity("SyncJob2","SyncJobGroup")
.Build();
ITrigger trigger2 = TriggerBuilder.Create()
.WithCronSchedule("0/15 * * * * ? *")
.WithIdentity("SyncJob2", "SyncJobGroup")
.Build();
await _scheduler.ScheduleJob(job, trigger);
await _scheduler.ScheduleJob(job2, trigger2);
await _scheduler.Start();
}
public async Task StopScheduler()
{
this._scheduler?.Shutdown(true).Wait(30000);
this._scheduler = null;
}
}
5—startup.cs配置
最后将quartZ相关服务添加到服务中。
public void ConfigureServices(IServiceCollection services)
{
//...
//注入定时任务调度中心
services.AddSingleton<SchedulerCenter>();
//注入任何工厂及调度工厂
services.AddSingleton<IJobFactory, SyncJobFactory>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
services.AddTransient<SyncJob>();
//...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment
env,IHostApplicationLifetime applicationLifetime)
{
//...
var quartz = app.ApplicationServices.GetRequiredService<SchedulerCenter>();
applicationLifetime.ApplicationStarted.Register(async () =>
{
quartz.StartScheduler(); //项目启动后,启动定时自动调度中心
});
applicationLifetime.ApplicationStopped.Register(async () =>
{
await quartz.StopScheduler(); //项目终止后,关闭任务调度中心
});
}
注意:IIS默认web站有低访问回收机制(即站重启),这样会导致web站的quartZ定时任务失效, 需要将自动回收机制取消,下图为网络搜索而来
- 打开该站的应用程序池的高级设置
- 设定相关的值为0。