组成
任务(Job)
- Job就是执行的作业,Job需要继承IJob接口,实现Execute方法。Job中执行的参数从Execute方法的参数中获取
触发器(Trigger)
SimpleTrigger触发器
CronTrigger触发器
调度器(Schedule)
- 调度器就是将任务和触发器绑定,让触发器触发的时候去执行任务
使用
在Startup文件中注入ISchedulerFactory的实例
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddMvc();
////注册ISchedulerFactory的实例。
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
}
使用注入的服务
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Quartz;
using QuartzDemo.Models;
using System.Threading.Tasks;
namespace QuartzDemo.Controllers
{
public class HomeController : Controller
{private readonly ISchedulerFactory _schedulerFactory;
private IScheduler _scheduler;
public HomeController(ISchedulerFactory schedulerFactory)
{
this._schedulerFactory = schedulerFactory;
}
public async Task<IActionResult> Index()
{
//通过调度工厂获得调度器
_scheduler = await _schedulerFactory.GetScheduler();
//开启调度器
await _scheduler.Start();
//创建一个触发器
var trigger = TriggerBuilder.Create()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever())//每两秒执行一次
.Build();
//创建任务
var jobDetail = JobBuilder.Create<MyJob>()
.WithIdentity("job", "group")
.Build();
//将触发器和任务器绑定到调度器中
await _scheduler.ScheduleJob(jobDetail, trigger);
return View();
}
}
}
using Quartz;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace QuartzDemo.Models
{
/// <summary>
/// 创建IJob的实现类,并实现Excute方法
/// </summary>
public class MyJob : IJob
{
public Task Execute(IJobExecutionContext context)
{
return Task.Run(() =>
{
using (StreamWriter sw = new StreamWriter(@"C:\Users\lenovo\Desktop\1.txt", true, Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
}
});
}
}
}
总结
通过演示可以看出,要执行一个定时任务,一般需要四步: