Quartz 简单用法

1、Nuget 初始化 Quartz包

右键单击项目下面的依赖项->管理nuget包->浏览然后搜索Quartz然后选择后面的安装(我安装的是3.0.4版本)在弹出来的接受许可证中选择我接受。

新建一个ReportJob类并实现IJob接口(如下所示)

 

 [PersistJobDataAfterExecution]
    [DisallowConcurrentExecution]
    public class ReportJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            var reportDirectory = string.Format("~/reports/{0}/", DateTime.Now.ToString("yyyy-MM"));
            reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory);
            if (!Directory.Exists(reportDirectory))
            {
                Directory.CreateDirectory(reportDirectory);
            }
            var dailyReportFullPath = string.Format("{0}report_{1}.log", reportDirectory, DateTime.Now.Day);
            var logContent = string.Format("{0}==>>{1}{2}", DateTime.Now, "create new log.", Environment.NewLine);
           
             return Task.Factory.StartNew(() => File.AppendAllText(dailyReportFullPath, logContent));
        }
    }

定时启动方法如下所示

public static async Task RunScheduler()
        {
            try
            {
                IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();
                //启动
                CronScheduleBuilder builder = CronScheduleBuilder.CronSchedule("30 * * * * ?");//每半分钟触发任务
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger", "group")
                    .StartNow()
                    .WithSchedule(builder)
                    .Build();
                IJobDetail job = JobBuilder.Create()//没半分钟执行一次Myclass里面的start方法
                    .WithIdentity("job", "group")
                    .Build();
                //加入这个调度
                await scheduler.ScheduleJob(job, trigger);

                //开启调度
                await scheduler.Start();
                //关闭调度
                //await scheduler.Shutdown(true);
            }
            catch (SchedulerException se)
            {
                Console.WriteLine(se);
            }

        }

调用定时任务的代码如下所示

RunScheduler().GetAwaiter().GetResult();

如此一个简单的定时任务就完成了。

你可能感兴趣的:(Asp.net)