quartz.net c#:如何通过JobDataMap将外部变量传递给作业

时间:2018-06-06 12:29:58

标签: c# asp.net-mvc quartz-scheduler autofac autofac-configuration

我在项目中使用autofac和工作单元/ Repository,我也使用Quartz.Net。

现在我写了一份工作,在我的工作代码中,我需要访问存储库。

我写的课程用于 Globl.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using Quartz.Impl;
using ServiceLayer;

namespace Web.Utility.Scheduler
{
    public class CheckProgramFinalizeScheduler
    {
        private static IService _service;

        public CheckProgramFinalizeScheduler(IService service)
        {
            _service = service;
        }

        public static void Start()
        {

            IJobDetail job = JobBuilder.Create<CheckProgramFinalizeJob>()
                .WithIdentity("checkFitnessplanJob", "fitnessPlan").UsingJobData("service",_service).Build();

            ITrigger trigger = TriggerBuilder.Create().WithIdentity("checkFitnessplanTrigger", "fitnessPlan")
                .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(23, 59)).ForJob(job).Build();

        }
    }
}

UsingJobData 预定义类型(不接受IService /不包含IService).UsingJobData("service",_service).

如何将实例IService传递给我的工作?

我的工作:

 public class CheckProgramFinalizeJob:IJob
    {
        public Task Execute(IJobExecutionContext context)
        {

            JobDataMap dataMap = context.JobDetail.JobDataMap;

            IService _service =(IService) dataMap.Get("service");

            var allCoachUnFinalized = _service.FitnessPlanRepository.GetAll(null,
                new Expression<Func<FitnessPlan, bool>>[]
                    {fp => fp.CoachFinalize == false && fp.PaymentStatus == PaymentStatusType.Paid}, null).List;

            foreach (var fitnessPlan in allCoachUnFinalized)
            {
                if (fitnessPlan.PayDate.Day - DateTime.Now.Day > 3)
                {
                    var user = _service.UserRepository.Get(null,
                        new Expression<Func<User, bool>>[] {u => u.Id == fitnessPlan.UserId},u=>u.UserFinancial);
                    var coach = _service.UserCoachRepository.Get(null,
                        new Expression<Func<UserCoach, bool>>[] {uc => uc.Id == fitnessPlan.UserCoachId},uc=>uc.CoachSetting);

                    var amount = fitnessPlan.WithDiet
                        ? fitnessPlan.UserCoach.CoachSetting.DietPrice +
                          fitnessPlan.UserCoach.CoachSetting.FitnessPlanPrice
                        : fitnessPlan.UserCoach.CoachSetting.FitnessPlanPrice;

                    user.UserFinancial.FinancialInventory += (long)amount;
                    _service.FitnessPlanRepository.Remove(fitnessPlan);

                }
            }

            return Task.CompletedTask;
        }
    }

0 个答案:

没有答案