asp.net core + Quartz.Net

Quartz.Net文檔地址:https://www.quartz-scheduler.net/documentation/index.html

參考:http://www.cnblogs.com/mi12205599/p/10361763.html

Quartz.Net 任務(wù)監(jiān)聽:http://www.itdecent.cn/p/ef1b6d1e11b2

本文源碼地址:https://gitee.com/forestGzh/Gzh.Template.Core

實(shí)現(xiàn)效果:

image.png

在Startup中配置:(具體實(shí)現(xiàn)看源碼)

在控制器中創(chuàng)建作業(yè)調(diào)度:(具體實(shí)現(xiàn)看源碼)

namespace Gzh.Template.Core.WebApi.Controllers

{

    [Route("api/[controller]")]

    public class TestQuartzController : Controller

    {

        private readonly ISchedulerFactory _schedulerFactory;

        private IScheduler _scheduler;

        public TestQuartzController(ISchedulerFactory schedulerFactory)

        {

            _schedulerFactory = schedulerFactory;

            _helloJobService = helloJobService;

        }

        /// <summary>

        /// Tests the quartz.

        /// </summary>

        /// <returns>The quartz.</returns>

        [HttpGet("testQuartz")]

        public async Task<ActionResult> TestQuartz()

        {

            //1、通過調(diào)度工廠獲得調(diào)度器

            _scheduler = await _schedulerFactory.GetScheduler();

            //2、開啟調(diào)度器

            await _scheduler.Start();

            //3、創(chuàng)建一個觸發(fā)器

            var trigger = TriggerBuilder.Create()

              .WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever())//每兩秒執(zhí)行一次

              .Build();

            //4、創(chuàng)建任務(wù)

            var jobDetail = JobBuilder.Create<HelloJobTest>()

              .WithIdentity("job", "group")

              .Build();

            //5、將觸發(fā)器和任務(wù)器綁定到調(diào)度器中

            await _scheduler.ScheduleJob(jobDetail, trigger);

            return Ok();

        }

    }

}

添加、啟動、刪除作業(yè)調(diào)度:

作業(yè)調(diào)度實(shí)體類:(具體實(shí)現(xiàn)看源碼)

using System;

using System.ComponentModel.DataAnnotations.Schema;

using Gzh.Template.Core.Repository.Core;

namespace Gzh.Template.Core.Repository.Domain.MysqlEntity

{

    public class ScheduleEntity : EntityMysql

    {

        /// <summary>

        /// Job的Key,在組內(nèi)唯一

        /// </summary>

        /// <value>The job key.</value>

        [Column("job_key")]

        public string JobKey { get; set; }

        /// <summary>

        /// Job的組名

        /// </summary>

        /// <value>The job group.</value>

        [Column("job_group")]

        public string JobGroup { get; set; }

        /// <summary>

        /// trigger的Key,在組內(nèi)唯一

        /// </summary>

        /// <value>The trigger key.</value>

        [Column("trigger_key")]

        public string TriggerKey { get; set; }

        /// <summary>

        /// trigger的組名

        /// </summary>

        /// <value>The trigger group.</value>

        [Column("trigger_group")]

        public string TriggerGroup { get; set; }

        /// <summary>

        /// 創(chuàng)建時間

        /// </summary>

        /// <value>The time create.</value>

        [Column("time_create")]

        public DateTime TimeCreate { get; set; }

        /// <summary>

        /// 開始執(zhí)行時間

        /// </summary>

        /// <value>The time start.</value>

        [Column("time_start")]

        public DateTime TimeStart { get; set; }

        /// <summary>

        /// 結(jié)束時間

        /// </summary>

        /// <value>The time end.</value>

        [Column("time_end")]

        public DateTime TimeEnd { get; set; }

        /// <summary>

        /// 重復(fù)執(zhí)行次數(shù)

        /// </summary>

        /// <value>The repet count.</value>

        [Column("repeat_count")]

        public int RepeatCount { get; set; }

        /// <summary>

        /// 運(yùn)行狀態(tài)

        /// </summary>

        /// <value>The state of the run.</value>

        [Column("run_state")]

        public string RunState { get; set; }

        /// <summary>

        /// 任務(wù)描述

        /// </summary>

        /// <value>The job description.</value>

        [Column("job_description")]

        public string JobDescription { get; set; }

    }

}

對HelloJob這個作業(yè)的調(diào)度:(具體實(shí)現(xiàn)看源碼)

using System;

using System.Threading.Tasks;

using Gzh.Template.Core.Repository.Domain.MysqlEntity;

namespace Gzh.Template.Core.Application.IService

{

    public interface IHelloJobService

    {

        /// <summary>

        /// 添加一個job

        /// </summary>

        /// <returns>The schedule job.</returns>

        /// <param name="scheduleEntity">Schedule entity.</param>

        Task<ScheduleEntity> AddScheduleJob(ScheduleEntity scheduleEntity);

        /// <summary>

        /// 運(yùn)行一個job

        /// </summary>

        /// <returns><c>true</c>, if schedule job was run, <c>false</c> otherwise.</returns>

        /// <param name="scheduleEntity">Schedule entity.</param>

        Task<bool> RunScheduleJobAsync(ScheduleEntity scheduleEntity);

        /// <summary>

        /// 停止并刪除一個job

        /// </summary>

        /// <returns><c>true</c>, if schedule job was stoped, <c>false</c> otherwise.</returns>

        /// <param name="scheduleEntity">Schedule entity.</param>

        Task<bool> RemoveScheduleJobAsync(ScheduleEntity scheduleEntity);

        /// <summary>

        /// 暫停一個job

        /// </summary>

        /// <returns><c>true</c>, if schedule was paused, <c>false</c> otherwise.</returns>

        /// <param name="scheduleEntity">Schedule entity.</param>

        Task<bool> PauseScheduleJobAsync(ScheduleEntity scheduleEntity);

    }

}

HelloJob(實(shí)現(xiàn)job,trigger和scheduler的Listener):

https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/trigger-and-job-listeners.html

https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/scheduler-listeners.html

using System;

using System.Threading;

using System.Threading.Tasks;

using Microsoft.Extensions.Logging;

using Quartz;

namespace Gzh.Template.Core.Application.Jobs

{

    /// <summary>

    /// quartz的作業(yè)類,在QuartzStartup中添加到調(diào)度程序中

    /// </summary>

    public class HelloJob : IJob, IJobListener, ITriggerListener, ISchedulerListener

    {

        private readonly ILogger _logger;

        public string Name { get; }

        public HelloJob(ILoggerFactory loggerFactory)

        {

            Name = this.GetType().ToString();

            _logger = loggerFactory.CreateLogger<QuartzStartup>();

        }

        //實(shí)現(xiàn)IJob接口的Excute方法

        public async Task Execute(IJobExecutionContext context)

        {

            //context.

            _logger.LogInformation("job名稱:" + context.JobDetail.Key

                + "\n trigger開始時間:" + context.Trigger.StartTimeUtc

                + "\n trigger結(jié)束時間:" + context.Trigger.EndTimeUtc

                + "\n 當(dāng)前時間:" + DateTime.Now

                + "\n 當(dāng)前觸發(fā)時間:" + context.ScheduledFireTimeUtc

                + "\n 下次觸發(fā)時間:" + context.NextFireTimeUtc

                + "\n 傳遞的數(shù)據(jù):" + context.JobDetail.JobDataMap["name"]

                );

            //await Console.Out.WriteLineAsync("Hello Job" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

        }

        #region

        public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken)

        {

            _logger.LogInformation("任務(wù)執(zhí)行失敗,重新執(zhí)行");

            //任務(wù)執(zhí)行失敗,再次執(zhí)行任務(wù)

            await Execute(context);

        }

        public async Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken)

        {

            _logger.LogInformation("準(zhǔn)備執(zhí)行任務(wù)");

            //return null;

        }

        public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken)

        {

            _logger.LogInformation("任務(wù)執(zhí)行完成");

        }

        #endregion

        #region

        public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken)

        {

            _logger.LogInformation("觸發(fā)器觸發(fā)成功 \n ------------------------------------------------------------------------------------------------------------------");

        }

        public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken)

        {

            _logger.LogInformation("觸發(fā)器開始觸發(fā)");

        }

        public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken)

        {

            _logger.LogInformation("觸發(fā)器觸發(fā)失敗");

        }

        public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken)

        {

            _logger.LogInformation("可以阻止任務(wù)執(zhí)行");

            //true 阻止,false 不阻止

            return false;

        }

        #endregion

        #region

        public async Task JobScheduled(ITrigger trigger, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobScheduled");

        }

        public async Task JobUnscheduled(TriggerKey triggerKey, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobUnscheduled");

        }

        public async Task TriggerFinalized(ITrigger trigger, CancellationToken cancellationToken)

        {

            _logger.LogInformation("TriggerFinalized");

        }

        public async Task TriggerPaused(TriggerKey triggerKey, CancellationToken cancellationToken)

        {

            _logger.LogInformation("TriggerPaused");

        }

        public async Task TriggersPaused(string triggerGroup, CancellationToken cancellationToken)

        {

            _logger.LogInformation("TriggersPaused");

        }

        public async Task TriggerResumed(TriggerKey triggerKey, CancellationToken cancellationToken)

        {

            _logger.LogInformation("TriggerResumed");

        }

        public async Task TriggersResumed(string triggerGroup, CancellationToken cancellationToken)

        {

            _logger.LogInformation("TriggersResumed");

        }

        public async Task JobAdded(IJobDetail jobDetail, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobAdded");

        }

        public async Task JobDeleted(JobKey jobKey, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobDeleted");

        }

        public async Task JobPaused(JobKey jobKey, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobPaused");

        }

        public async Task JobInterrupted(JobKey jobKey, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobInterrupted");

        }

        public async Task JobsPaused(string jobGroup, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobsPaused");

        }

        public async Task JobResumed(JobKey jobKey, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobResumed");

        }

        public async Task JobsResumed(string jobGroup, CancellationToken cancellationToken)

        {

            _logger.LogInformation("JobsResumed");

        }

        public async Task SchedulerError(string msg, SchedulerException cause, CancellationToken cancellationToken)

        {

            _logger.LogInformation("SchedulerError");

        }

        public async Task SchedulerInStandbyMode(CancellationToken cancellationToken)

        {

            _logger.LogInformation("SchedulerInStandbyMode");

        }

        public async Task SchedulerStarted(CancellationToken cancellationToken)

        {

            _logger.LogInformation("SchedulerStarted");

        }

        public async Task SchedulerStarting(CancellationToken cancellationToken)

        {

            _logger.LogInformation("SchedulerStarting");

        }

        public async Task SchedulerShutdown(CancellationToken cancellationToken)

        {

            _logger.LogInformation("SchedulerShutdown");

        }

        public async Task SchedulerShuttingdown(CancellationToken cancellationToken)

        {

            _logger.LogInformation("SchedulerShuttingdown");

        }

        public async Task SchedulingDataCleared(CancellationToken cancellationToken)

        {

            _logger.LogInformation("SchedulingDataCleared");

        }

        #endregion

    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容