ABP Quartz.NET “最佳“实践-2 执行任务

在实践1中,注册了Job,它的代码如下。一方面它实现了IJob接口,另外也可以根据需要使用系统注入的服务等。

//本方法仅为示意
//实现IJob接口 
public class SimpleJob :  IJob
    {
        //系统提供的服务
        private readonly XXXAppService  xxxAppService;

        //构造函数,接受系统注入的服务
        public SimpleJob (XXXAppService  xxxAppService)
        {
            this.xxxAppService = xxxAppService;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            //根据任务环境上下文获取相关任务信息
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            //调用服务方法
            await xxxAppService .DoSomething(dataMap);
          
            await Task.CompletedTask;

        }
    }

 更近一步,怎么创建Job呢。

1、获取注入的ISchedulerFactory;

2、创建任务和触发器。

下面给了一个相对复杂点的代码,可以根据自己的实际情况参考Quartz.net的代码进行编码。

public JobService()
{
    private ISchedulerFactory _schedulerFactory;
    private IScheduler _scheduler;

    //获取注入的ISchedulerFactory 
    public JobService(ISchedulerFactory schedulerFactory)
    {
        _schedulerFactory=schedulerFactory;
        _scheduler = schedulerFactory.GetScheduler().Result;
    }

    //创建任务。本例比较复杂通过Type.GetType获取到任务类,并使用了Corn表达式。
    public async Task<ScheduleResult> AddJobAsync(String JobName, String JobGroup, 
    String JobNamespaceAndClassName, String JobAssemblyName, string CronExpress, DateTime? StartTime, DateTime? EndTime)
    {
        ScheduleResult result = new ScheduleResult();
        try
        {
            if (string.IsNullOrEmpty(JobName) || string.IsNullOrEmpty(JobGroup) || string.IsNullOrEmpty(JobNamespaceAndClassName) || string.IsNullOrEmpty(JobAssemblyName) || string.IsNullOrEmpty(CronExpress))
            {
                result.Code = -3;
                result.Message = $"参数不能为空";
                return result;//出现异常
            }
            if (StartTime == null)
            {
                StartTime = DateTime.Now;
            }
            DateTimeOffset startRunTime = DateBuilder.NextGivenSecondDate(StartTime, 1);
            if (EndTime == null)
            {
                EndTime = DateTime.MaxValue.AddDays(-1);
            }
            DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(EndTime, 1);
            JobKey jobKey = new JobKey(JobName, JobGroup);
            if (await _scheduler.CheckExists(jobKey))
            {
                await _scheduler.PauseJob(jobKey);
                await _scheduler.DeleteJob(jobKey);
            }
            //这里使用Type.GetType通过SimpleJob的集合名称,命名空间和类名获取到。
            var jobType = Type.GetType(JobNamespaceAndClassName + "," + JobAssemblyName);
          
          
            if (jobType == null)
            {
                result.Code = -1;
                result.Message = "系统找不到对应的任务,请重新设置";
                return result;//出现异常
            }
       
            IJobDetail job = JobBuilder.Create(jobType)
            .WithIdentity(jobKey).UsingJobData("ServerName", _scheduler.SchedulerName)
            .Build();
            //使用了CronTrigger
            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                         .StartAt(startRunTime)
                                         //.EndAt(endRunTime)
                                         .WithIdentity(JobName, JobGroup)
                                         .WithCronSchedule(CronExpress, x =>                 x.InTimeZone(TimeZoneInfo.Local))                                           
                                         .Build();
            await _scheduler.ScheduleJob(job, trigger);
            if (!_scheduler.IsStarted)
            {
                await _scheduler.Start();
            }
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogException(ex);
            result.Code = -4;
            result.Message = ex.ToString();
            return result;//出现异常
        }
    }


    
}

当然关于任务的停止,恢复,删除就不在此一一列举了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值