Beispiel #1
0
        public void Execute(JobExecutionContext context)
        {
            int tryNumber = context.JobDetail.JobDataMap.GetIntValue(RetryableJobListener.NumberTriesJobDataMapKey);
            Console.WriteLine("{0} - Executing dummy job. This is try number {1} of {2}", DateTime.UtcNow, tryNumber, MaxNumberTries);

            throw new JobExecutionException("This job is too dumb to execute!");
        }
	    /// <summary>
		/// Called by the <see cref="IScheduler" /> when a <see cref="Trigger" />
		/// fires that is associated with the <see cref="IJob" />.
		/// <p>
		/// The implementation may wish to set a  result object on the
		/// JobExecutionContext before this method exits.  The result itself
		/// is meaningless to Quartz, but may be informative to
		/// <see cref="IJobListener" />s or
		/// <see cref="ITriggerListener" />s that are watching the job's
		/// execution.
		/// </p>
		/// </summary>
		/// <param name="context">The execution context.</param>
		/// <seealso cref="IJob">
		/// </seealso>
		public virtual void Execute(JobExecutionContext context)
		{
			JobDataMap data = context.MergedJobDataMap;
			SchedulerContext schedCtxt;
			try
			{
				schedCtxt = context.Scheduler.Context;
			}
			catch (SchedulerException e)
			{
				throw new JobExecutionException("Error obtaining scheduler context.", e, false);
			}

			string fileName = data.GetString(FileName);
			string listenerName = data.GetString(FileScanListenerName);

			if (fileName == null)
			{
				throw new JobExecutionException(string.Format(CultureInfo.InvariantCulture, "Required parameter '{0}' not found in JobDataMap", FileName));
			}
			if (listenerName == null)
			{
				throw new JobExecutionException(string.Format(CultureInfo.InvariantCulture, "Required parameter '{0}' not found in JobDataMap", FileScanListenerName));
			}

			IFileScanListener listener = (IFileScanListener) schedCtxt[listenerName];

			if (listener == null)
			{
				throw new JobExecutionException(string.Format(CultureInfo.InvariantCulture, "FileScanListener named '{0}' not found in SchedulerContext", listenerName));
			}

			DateTime lastDate = DateTime.MinValue;
			if (data.Contains(LastModifiedTime))
			{
				lastDate = data.GetDateTime(LastModifiedTime);
			}

			DateTime newDate = GetLastModifiedDate(fileName);

			if (newDate == DateTime.MinValue)
			{
				Log.Warn(string.Format(CultureInfo.InvariantCulture, "File '{0}' does not exist.", fileName));
				return;
			}

			if (lastDate != DateTime.MinValue && (newDate != lastDate))
			{
				// notify call back...
				Log.Info(string.Format(CultureInfo.InvariantCulture, "File '{0}' updated, notifying listener.", fileName));
				listener.FileUpdated(fileName);
			}
			else
			{
				Log.Debug(string.Format(CultureInfo.InvariantCulture, "File '{0}' unchanged.", fileName));
			}

			context.JobDetail.JobDataMap.Put(LastModifiedTime, newDate);
		}
 public void ConstructorSetsProperties()
 {
     JobExecutionContext context = new JobExecutionContext(scheduler, logger, jobSpec, jobData);
     Assert.AreSame(scheduler, context.Scheduler);
     Assert.AreSame(logger, context.Logger);
     Assert.AreSame(jobSpec, context.JobSpec);
     Assert.AreSame(jobData, context.JobData);
 }
Beispiel #4
0
 /// <summary>
 /// Jobs the was executed.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="jobException">The job exception.</param>
 public void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException)
 {
     if (jobException != null)
     {
         Inject();
         Logger.Log(LogSeverity.Error, GetType().ToString(), jobException);
     }
 }
		/// <summary>
		/// Executes the job.
		/// </summary>
		/// <param name="context">The job execution context.</param>
		public virtual void Execute(JobExecutionContext context)
		{
			JobDataMap data = context.JobDetail.JobDataMap;

			string smtpHost = data.GetString(PropertySmtpHost);
			string to = data.GetString(PropertyRecipient);
			string cc = data.GetString(PropertyCcRecipient);
			string from = data.GetString(PropertySender);
			string replyTo = data.GetString(PropertyReplyTo);
			string subject = data.GetString(PropertySubject);
			string message = data.GetString(PropertyMessage);

			if (smtpHost == null || smtpHost.Trim().Length == 0)
			{
				throw new ArgumentException("PropertySmtpHost not specified.");
			}
			if (to == null || to.Trim().Length == 0)
			{
				throw new ArgumentException("PropertyRecipient not specified.");
			}
			if (from == null || from.Trim().Length == 0)
			{
				throw new ArgumentException("PropertySender not specified.");
			}
			if (subject == null || subject.Trim().Length == 0)
			{
				throw new ArgumentException("PropertySubject not specified.");
			}
			if (message == null || message.Trim().Length == 0)
			{
				throw new ArgumentException("PropertyMessage not specified.");
			}

			if (cc != null && cc.Trim().Length == 0)
			{
				cc = null;
			}

			if (replyTo != null && replyTo.Trim().Length == 0)
			{
				replyTo = null;
			}

			string mailDesc = string.Format(CultureInfo.InvariantCulture, "'{0}' to: {1}", subject, to);

			Log.Info(string.Format(CultureInfo.InvariantCulture, "Sending message {0}", mailDesc));

			try
			{
				SendMail(smtpHost, to, cc, from, replyTo, subject, message);
			}
			catch (Exception ex)
			{
				throw new JobExecutionException(string.Format(CultureInfo.InvariantCulture, "Unable to send mail: {0}", mailDesc), ex, false);
			}
		}
        private void ScheduleRetryableJob(JobExecutionContext context, IRetryableJob retryableJob)
        {
            var oldTrigger = context.Trigger;

            // Unschedule old trigger
            _scheduler.UnscheduleJob(oldTrigger.Name, oldTrigger.Group);

            // Create and schedule new trigger
            var retryTrigger = new SimpleTrigger(oldTrigger.Name, oldTrigger.Group, retryableJob.StartTimeRetryUtc, retryableJob.EndTimeRetryUtc, 0, TimeSpan.Zero);
            _scheduler.ScheduleJob(context.JobDetail, retryTrigger);
        }
        public void JobToBeExecuted(JobExecutionContext context)
        {
            var retryableJob = context.JobInstance as IRetryableJob;
            if (retryableJob == null)
                return;

            if (!context.JobDetail.JobDataMap.Contains(NumberTriesJobDataMapKey))
                context.JobDetail.JobDataMap[NumberTriesJobDataMapKey] = 0;

            int numberTries = context.JobDetail.JobDataMap.GetIntValue(NumberTriesJobDataMapKey);
            context.JobDetail.JobDataMap[NumberTriesJobDataMapKey] = ++numberTries;
        }
Beispiel #8
0
        protected override void ExecuteInternal(JobExecutionContext context)
        {
            logger.Info("日报表任务开始。。。");

            try
            {
                SPPaymentInfoWrapper.RendAllData(DateTime.Now.AddDays(-1));

                logger.Info("日报表任务成功。。。");
            }
            catch (Exception ex)
            {
                logger.Error("日报表任务失败:" + ex.Message);
            }
        }
Beispiel #9
0
        public void TestMethodInvoker_ShouldSetResultToExecutionContext()
        {
            InvocationCountingJob job = new InvocationCountingJob();
            MethodInvoker         mi  = new MethodInvoker();

            mi.TargetObject = job;
            mi.TargetMethod = "InvokeWithReturnValue";
            mi.Prepare();
            methodInvokingJob.MethodInvoker = mi;
            JobExecutionContext context = CreateMinimalJobExecutionContext();

            methodInvokingJob.Execute(context);

            Assert.AreEqual(InvocationCountingJob.DefaultReturnValue, context.Result, "result value was not set to context");
        }
 public void Execute(JobExecutionContext context)
 {
     ConsoleLog.WriteLog("补发订单数据到盈科大数据:SendOrderInfoToYKBDMqJob...begin");
     try
     {
         Jinher.AMP.BTP.ISV.Facade.CommodityOrderFacade facace = new ISV.Facade.CommodityOrderFacade();
         facace.SendOrderInfoToYKBDMq();
     }
     catch (Exception e)
     {
         ConsoleLog.WriteLog("Exception:" + e.Message, LogLevel.Error);
         ConsoleLog.WriteLog("Exception:" + e.StackTrace, LogLevel.Error);
     }
     ConsoleLog.WriteLog("补发订单数据到盈科大数据:SendOrderInfoToYKBDMqJob end");
 }
Beispiel #11
0
        protected override void ExecuteInternal(JobExecutionContext context)
        {
            logger.Info("日报表任务开始。。。");

            try
            {
                SPDayReportWrapper.ReGenerateDayReport(DateTime.Now.AddDays(-1));

                logger.Info("日报表任务成功。。。");
            }
            catch (Exception ex)
            {
                logger.Error("日报表任务失败:" + ex.Message);
            }
        }
Beispiel #12
0
        public void Execute(JobExecutionContext context)
        {
            if (JobStatus.TransformStatus == Status.Off)
            {
                JobStatus.TransformStatus = Status.On;

                _executor.Execute();

                JobStatus.TransformStatus = Status.Off;
            }
            else
            {
                _logger.Info("索引创建正在执行,系统将在下个运行时间运行!");
            }
        }
Beispiel #13
0
        void IJob.Execute(JobExecutionContext context)
        {
            ILog log = LogManager.GetLogger(typeof(jobAuthority_2));

            try
            {
                if (factory == null)
                {
                    cfg = new Configuration();
                    cfg.AddAssembly("BRIChannelSchedulerNew");
                    factory = cfg.BuildSessionFactory();
                }
                session = factory.OpenSession();
                Console.WriteLine(schInfo + SchCode + " === Starting " + SchName + " ===");

                try
                {
                    Commitjob_transaction(log);
                }
                catch (Exception ee)
                {
                    log.Error(SchCode + " === " + SchName + " Process Error Message:: " + ee.Message);
                    log.Error(SchCode + " === " + SchName + " Process Error Inner Exception:: " + ee.InnerException);
                    log.Error(SchCode + " === " + SchName + " Process Error StackTrace:: " + ee.StackTrace);
                }
                Console.WriteLine(schInfo + SchCode + " === End " + SchName + " ===");
            }
            catch (Exception ex)
            {
                log.Error(SchCode + " === " + SchName + " Failed To Start Message:: " + ex.Message);
                log.Error(SchCode + " === " + SchName + " Failed To Start Inner Exception:: " + ex.InnerException);
                log.Error(SchCode + " === " + SchName + " Failed To Start StackTrace:: " + ex.StackTrace);
            }
            finally
            {
                if (session.IsOpen)
                {
                    session.Clear();
                    session.Close();
                    session.Dispose();
                }
                factory.Close();
                factory.Dispose();

                cfg = null;
                GC.Collect();
            }
        }
Beispiel #14
0
        public void Execute(JobExecutionContext context)
        {
            Logger.Log.Debug("Start Importing KenhNhaTro Job...");

            DateTime dateStart = DateTime.Today;
            //if (dateStart.DayOfWeek == DayOfWeek.Monday)
            //{
            //    dateStart = dateStart.AddDays(-2);
            //}
            DateTime dateEnd = DateTime.Today;

            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/huyen-hoc-mon/tp-ho-chi-minh.html", 1, "Huyện Hóc Môn", 18, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/huyen-can-gio/tp-ho-chi-minh.html", 1, "Huyện Cần Giờ", 80, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/huyen-nha-be/tp-ho-chi-minh.html", 1, "Huyện Nhà Bè", 20, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/huyen-cu-chi/tp-ho-chi-minh.html", 1, "Huyện Củ Chi", 80, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/huyen-binh-chanh/tp-ho-chi-minh.html", 1, "Huyện Bình Chánh", 19, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-binh-tan/tp-ho-chi-minh.html", 1, "Quận Bình Tân", 79, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-thu-duc/tp-ho-chi-minh.html", 1, "Quận Thủ Đức", 17, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-go-vap/tp-ho-chi-minh.html", 1, "Quận Gò Vấp", 16, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-tan-phu/tp-ho-chi-minh.html", 1, "Quận Tân Phú", 15, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-tan-binh/tp-ho-chi-minh.html", 1, "Quận Tân Bình", 14, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-binh-thanh/tp-ho-chi-minh.html", 1, "Quận Bình Thạnh", 21, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-phu-nhuan/tp-ho-chi-minh.html", 1, "Quận Phú Nhuận", 13, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-12/tp-ho-chi-minh.html", 1, "Quận 12", 12, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-11/tp-ho-chi-minh.html", 1, "Quận 11", 11, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-10/tp-ho-chi-minh.html", 1, "Quận 10", 10, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-9/tp-ho-chi-minh.html", 1, "Quận 9", 9, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-8/tp-ho-chi-minh.html", 1, "Quận 8", 8, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-7/tp-ho-chi-minh.html", 1, "Quận 7", 7, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-6/tp-ho-chi-minh.html", 1, "Quận 6", 6, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-5/tp-ho-chi-minh.html", 1, "Quận 5", 5, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-4/tp-ho-chi-minh.html", 1, "Quận 4", 4, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-3/tp-ho-chi-minh.html", 1, "Quận 3", 3, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-2/tp-ho-chi-minh.html", 1, "Quận 2", 2, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-1/tp-ho-chi-minh.html", 1, "Quận 1", 1, dateStart, dateEnd);

            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-cam-le/da-nang.html", 4, "Cam Le", 82, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-hai-chau/da-nang.html", 4, "Hai Chau", 83, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-lien-chieu/da-nang.html", 4, "Lien Chieu", 84, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-ngu-hanh-son/da-nang.html", 4, "Ngu Hanh Son", 85, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-son-tra/da-nang.html", 4, "Son Tra", 86, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-thanh-khe/da-nang.html", 4, "Thanh Khe", 87, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-hoa-vang/da-nang.html", 4, "Hoa Vang", 88, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/quan-hoang-sa/da-nang.html", 4, "Hoang Sa", 89, dateStart, dateEnd);
            GetPostForOneDistrict("http://kenhnhatro.com/cho-thue-phong-tro-nha-tro/thanh-pho-nha-trang/khanh-hoa.html", 6, "Nha Trang", 90, dateStart, dateEnd);

            Logger.Log.Debug("End Importing KenhNhaTro Job...");
        }
Beispiel #15
0
        private bool NotifyJobListenersComplete(JobExecutionContext ctx, JobExecutionException jobExEx)
        {
            try
            {
                qs.NotifyJobListenersWasExecuted(ctx, jobExEx);
            }
            catch (SchedulerException se)
            {
                qs.NotifySchedulerListenersError(
                    string.Format(CultureInfo.InvariantCulture, "Unable to notify JobListener(s) of Job that was executed: (error will be ignored). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);

                return(false);
            }

            return(true);
        }
Beispiel #16
0
 public void Execute(JobExecutionContext context)
 {
     ConsoleLog.WriteLog("处理活动过期未支付订单:OrderExpirePayJob...begin");
     try
     {
         Jinher.AMP.BTP.ISV.Facade.CommodityOrderFacade facace = new ISV.Facade.CommodityOrderFacade();
         //处理活动过期订单
         facace.AutoExpirePayOrder();
     }
     catch (Exception e)
     {
         ConsoleLog.WriteLog("Exception:" + e.Message, LogLevel.Error);
         ConsoleLog.WriteLog("Exception:" + e.StackTrace, LogLevel.Error);
     }
     ConsoleLog.WriteLog("处理活动过期未支付订单:OrderExpirePayJob end");
 }
Beispiel #17
0
 public void Execute(JobExecutionContext context)
 {
     try
     {
         lock (context)
         {
             object    mo = context.JobDetail.JobDataMap.Get("Monitor");
             MonitorUI mu = (MonitorUI)mo;
             mu.ConnectOssClient();
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error(ex.Message);
     }
 }
Beispiel #18
0
        /// <summary>
        /// Entry point called when trigger fires.
        /// </summary>
        /// <param name="context"></param>
        public void Execute(JobExecutionContext context)
        {
            var settings = Load(context);

            try
            {
                Store.Mdns.RemoveDispositions(TimeSpan.FromDays(settings.Days), settings.BulkCount);
            }
            catch (Exception e)
            {
                Logger.Error("Error in job!");
                Logger.Error(e.Message);
                var je = new JobExecutionException(e);
                throw je;
            }
        }
    public void Execute(JobExecutionContext context)
    {
        string instName  = context.JobDetail.Name;
        string instGroup = context.JobDetail.Group;

        // Note the difference from the previous example
        JobDataMap dataMap = context.MergedJobDataMap;

        string    jobSays      = dataMap.GetString("jobSays");
        float     myFloatValue = dataMap.GetFloat("myFloatValue");
        ArrayList state        = (ArrayList)dataMap.Get("myStateData");

        state.Add(DateTime.UtcNow);

        Console.WriteLine("Instance {0} of DumbJob says: {1}", instName, jobSays);
    }
Beispiel #20
0
        /// <summary>
        /// 企业合同到期的提醒发给所有的内部人员
        /// </summary>
        /// <param name="context"></param>
        protected override void ExecuteDetails(JobExecutionContext context)
        {
            int daysOffToday = 3;

            if (SystemTaskInConfig != null)
            {
                daysOffToday = Converter.ChangeType(SystemTaskInConfig.GetAddonItemValue("aheadDays"), 7);
            }

            DateTime dateLower = DateTime.Today.AddDays(daysOffToday);
            DateTime dateUpper = dateLower.AddDays(1);

            List <EnterpriseContractEntity> enterpriseContractList = EnterpriseContractBLL.Instance.GetList(string.Format("[ContractStatus] ={0} AND ContractStopDate>= '{1}'  AND ContractStopDate<'{2}' ", (int)Logics.True, dateLower, dateUpper));

            DispatchRemindMessage(enterpriseContractList);
        }
Beispiel #21
0
 public void Execute(JobExecutionContext context)
 {
     ConsoleLog.WriteLog("处理追踪物流过程:OTMSJob...begin");
     try
     {
         BTP.IBP.Facade.OrderExpressRouteFacade oerFacade = new BTP.IBP.Facade.OrderExpressRouteFacade();
         oerFacade.GetOrderExpressForJdJob();
         oerFacade.GetOrderExpressForJsJob();
     }
     catch (Exception e)
     {
         ConsoleLog.WriteLog("OTMSJobException:" + e.Message, LogLevel.Error);
         ConsoleLog.WriteLog("OTMSJobException:" + e.StackTrace, LogLevel.Error);
     }
     ConsoleLog.WriteLog("处理追踪物流过程:OTMSJob...end");
 }
 /// <summary>
 /// This implementation applies the passed-in job data map as object property
 /// values, and delegates to <code>ExecuteInternal</code> afterwards.
 /// </summary>
 /// <seealso cref="ExecuteInternal" />
 public void Execute(JobExecutionContext context)
 {
     try
     {
         ObjectWrapper         bw  = new ObjectWrapper(this);
         MutablePropertyValues pvs = new MutablePropertyValues();
         pvs.AddAll(context.Scheduler.Context);
         pvs.AddAll(context.MergedJobDataMap);
         bw.SetPropertyValues(pvs, true);
     }
     catch (SchedulerException ex)
     {
         throw new JobExecutionException(ex);
     }
     ExecuteInternal(context);
 }
Beispiel #23
0
 public void Execute(JobExecutionContext context)
 {
     ConsoleLog.WriteLog("全量同步京东价格--------------Begin");
     try
     {
         JdJobHelper.AutoUpdateJdPrice();
         JdJobHelper.AutoUpdateJdStock();
         JdJobHelper.AutoUpdateJdSkuState();
     }
     catch (Exception e)
     {
         ConsoleLog.WriteLog("Exception:" + e.Message, LogLevel.Error);
         ConsoleLog.WriteLog("Exception:" + e.StackTrace, LogLevel.Error);
     }
     ConsoleLog.WriteLog("全量同步京东价格--------------End");
 }
        public void Execute(JobExecutionContext context)
        {
            var state         = context.JobDetail.JobDataMap[StateKey];
            var clearTimeout  = context.JobDetail.JobDataMap.GetBoolean(ClearTimeoutKey);
            var expires       = context.JobDetail.JobDataMap.GetDateTime(ExpiresKey);
            var sagaId        = Guid.Parse(context.JobDetail.JobDataMap[SagaIdkey].ToString());
            var returnAddress = context.JobDetail.JobDataMap.GetString(ReturnAddressKey);

            Bus.Send(returnAddress, new[] { new TimeoutMessage()
                                            {
                                                Expires      = expires,
                                                ClearTimeout = clearTimeout,
                                                SagaId       = sagaId,
                                                State        = state
                                            } });
        }
Beispiel #25
0
        /// <summary>
        /// 작업이 완료(성공이던 실패던)되었을 때, 호출됩니다.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        public override void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException)
        {
            base.JobWasExecuted(context, jobException);

            if (jobException != null)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnException(string.Format("Job[{0}] 실행에 예외가 발생했습니다!!!", context.JobDetail.FullName), jobException);
                }
            }
            else if (IsDebugEnabled)
            {
                log.Debug(@"Job[{0}] 이 수행되었습니다.", context.JobDetail.FullName);
            }
        }
Beispiel #26
0
 public void Execute(JobExecutionContext context)
 {
     try
     {
         ConsoleLog.WriteLog("苏宁物流定时任务[Start]........" + DateTime.Now);
     }
     catch (Exception e)
     {
         ConsoleLog.WriteLog("苏宁物流Exception:" + e.Message, LogLevel.Error);
         ConsoleLog.WriteLog("苏宁物流Exception:" + e.StackTrace, LogLevel.Error);
     }
     finally
     {
         ConsoleLog.WriteLog("苏宁物流定时任务[End]........" + DateTime.Now);
     }
 }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="Trigger" />
        /// has fired, and it's associated <see cref="JobDetail" />
        /// is about to be executed.
        /// <p>
        /// It is called before the <see cref="VetoJobExecution" /> method of this
        /// interface.
        /// </p>
        /// </summary>
        /// <param name="trigger">The <see cref="Trigger" /> that has fired.</param>
        /// <param name="context">The <see cref="JobExecutionContext" /> that will be passed to the <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
        public virtual void TriggerFired(Trigger trigger, JobExecutionContext context)
        {
            if (!Log.IsInfoEnabled)
            {
                return;
            }

            object[] args =
                new object[]
            {
                trigger.Name, trigger.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), DateTime.UtcNow,
                context.JobDetail.Name, context.JobDetail.Group, context.RefireCount
            };

            Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerFiredMessage, args));
        }
Beispiel #28
0
        public bool VetoJobExecution(Trigger trigger, JobExecutionContext context)
        {
            if (!ShouldDispatch(trigger))
            {
                return(false);
            }

            foreach (ITriggerListener l in listeners)
            {
                if (l.VetoJobExecution(trigger, context))
                {
                    return(true);
                }
            }
            return(false);
        }
        public void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException)
        {
            if (jobException == null)
                return; 

            var retryableJob = context.JobInstance as IRetryableJob;
            if (retryableJob == null)
                return; 

            int numberTries = context.JobDetail.JobDataMap.GetIntValue(NumberTriesJobDataMapKey);
            if (numberTries >= retryableJob.MaxNumberTries)
                return; // Max number tries reached

            // Schedule next try
            ScheduleRetryableJob(context, retryableJob);
        }
Beispiel #30
0
        private bool IsTargetAlreadyBeingCollected(JobExecutionContext jobExecutionContext)
        {
            var candidateCollectRequestId = string.Empty;
            var candidateTargetAddress    = string.Empty;

            try
            {
                candidateCollectRequestId = jobExecutionContext.MergedJobDataMap.GetString(JobInfoFields.REQUEST_ID);
                candidateTargetAddress    = jobExecutionContext.MergedJobDataMap.GetString(JobInfoFields.TARGET_ADDRESS);
                Func <string, string, bool> requestsByTargetAddres =
                    (requestId, targetAddress) =>
                    requestId != candidateCollectRequestId && targetAddress == candidateTargetAddress;

                var schedulerController = new ScheduleController(jobExecutionContext.Scheduler);
                var allScheduledCollectionByTargetAddress =
                    schedulerController
                    .GetAllScheduledRequests()
                    .Where(req => requestsByTargetAddres(req.Key, req.Value.Key));

                if (allScheduledCollectionByTargetAddress.Count() == 0)
                {
                    return(false);
                }

                var runningCollectRequestsIds = allScheduledCollectionByTargetAddress.Select(x => x.Key);
                using (var session = Repository.GetSession())
                {
                    var collectRequestsInExecution =
                        Repository
                        .GetCollectRequests(session, runningCollectRequestsIds.ToArray())
                        .Where(req => req.Status == Contract.CollectRequestStatus.Executing);

                    return(collectRequestsInExecution.Count() > 0);
                }
            }
            catch (Exception ex)
            {
                LogError(
                    ERROR_ON_CHECKING_IF_TARGET_IS_ALREADY_BEING_COLLECTED,
                    candidateCollectRequestId,
                    candidateTargetAddress,
                    ex.Message,
                    ex.StackTrace);

                return(false);
            }
        }
        /// <summary>
        /// Job执行的具体实现
        /// </summary>
        /// <param name="context"></param>
        protected override void ExecuteDetails(JobExecutionContext context)
        {
            int daysOffToday = 3;

            if (SystemTaskInConfig != null)
            {
                daysOffToday = Converter.ChangeType(SystemTaskInConfig.GetAddonItemValue("aheadDays"), 3);
            }

            int dayOfYear = DateTime.Today.DayOfYear;
            int dateLower = dayOfYear + daysOffToday;
            int dateUpper = dateLower + 1;

            List <BusinessUser> birthdayUserList = BusinessUserBLL.GetList(string.Format("[UserType] ={0} AND DATEPART(DY,UserBirthDay)>= {1}  AND DATEPART(DY,UserBirthDay)<{2} ", (int)this.UserType, dateLower, dateUpper));

            DispatchRemindMessage(birthdayUserList);
        }
Beispiel #32
0
        private List <string> GetExecutingJobs()
        {
            IList         list          = _scheduler.GetCurrentlyExecutingJobs();
            List <string> executingJobs = new List <string>();

            foreach (var obj in list)
            {
                JobExecutionContext context = obj as JobExecutionContext;

                if (context != null)
                {
                    executingJobs.Add(context.JobDetail.Name);
                }
            }

            return(executingJobs);
        }
Beispiel #33
0
        public bool Enqueue(JobContext jobContext)
        {
            lock (this)
            {
                if (IsStopping || (ActiveThreads >= ThreadCount))
                {
                    return(false);
                }

                JobExecutionContext jobExecutionContext = new JobExecutionContext(jobContext, this);
                Thread thread = new Thread(ExecuteJob);
                jobExecutionContext.Thread = thread;
                workers.AddLast(jobExecutionContext);
                thread.Start(jobExecutionContext);
                return(true);
            }
        }
Beispiel #34
0
        public override void ProcessRecord(JobExecutionContext context)
        {
            var proxy  = context.Proxy;
            var record = context.Record;

            var email = record.GetAttributeValue <string>("emailaddress1");

            context.PushMetric("Email avant", email);

            email = email.ToLowerInvariant();
            email = email.Replace(DomainExtension, ".fake");

            context.PushMetric("Email apres", email);

            record["emailaddress1"] = email;
            proxy.Update(context.Record);
        }
Beispiel #35
0
        public void Execute(JobExecutionContext context)
        {
            var jdm      = context.JobDetail.JobDataMap;
            var timer_id = jdm.GetInt("timer_id");

            if (timer_id <= 0)
            {
                throw new Exception("Scheduler Exception: no hay timer_id para ejecutar el timer.");
            }
            var callback = jdm.Get("delegate") as Launch;

            if (callback == null)
            {
                throw new Exception("Scheduler Exception: no hay delegado para ejecutar el timer.");
            }
            callback(timer_id);
        }
Beispiel #36
0
        protected override void ExecuteInternal(JobExecutionContext context)
        {
            var startTime = DateTime.UtcNow;
            var logEntity = new SCHEDULERLOG {
                STARTTIME = startTime
            };

            var strInfo = new StringBuilder();

            strInfo.AppendFormat("<p>Source [Type: RSSL Host: 10.35.30.44:14002 ServiceName:ELEKTRON_DD]\n");

            strInfo.AppendFormat("Destination [Type: {0} Address: {1}]</p>", "Oracle",
                                 ConfigurationManager.AppSettings["BondDBCon"]);


            NewListBondFromRfa rfa = new NewListBondFromRfa();

            try
            {
                #region 执行数据同步程序
                if (DateTime.Now.Hour < 9 || DateTime.Now.Hour > 18)
                {
                    strInfo.Append("Only this time(9:00Am-6:00Pm) point synchronous;");
                    return;
                }
                logEntity.JobStatus = rfa.Run(strInfo);

                #endregion

                var endTime = DateTime.UtcNow;
                logEntity.ENDTIME   = endTime;
                logEntity.RUNDETAIL = strInfo.ToString();
                WriteLogEntity(logEntity);
            }
            catch (Exception exception)
            {
                logEntity.ENDTIME   = DateTime.UtcNow;
                logEntity.JobStatus = JobStatus.Fail;
                logEntity.RUNDETAIL = strInfo + "\n" + exception;
                WriteLogEntity(logEntity);
            }
            finally
            {
                rfa.Cleanup();
            }
        }
Beispiel #37
0
        private bool NotifyListenersBeginning(JobExecutionContext ctx)
        {
            bool vetoed;

            // notify all trigger listeners
            try
            {
                vetoed = qs.NotifyTriggerListenersFired(ctx);
            }
            catch (SchedulerException se)
            {
                qs.NotifySchedulerListenersError(
                    string.Format(CultureInfo.InvariantCulture, "Unable to notify TriggerListener(s) while firing trigger (Trigger and Job will NOT be fired!). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);

                return(false);
            }

            if (vetoed)
            {
                try
                {
                    qs.NotifyJobListenersWasVetoed(ctx);
                }
                catch (SchedulerException se)
                {
                    qs.NotifySchedulerListenersError(
                        string.Format(CultureInfo.InvariantCulture, "Unable to notify JobListener(s) of vetoed execution while firing trigger (Trigger and Job will NOT be fired!). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);
                }
                throw new VetoedException(this);
            }

            // notify all job listeners
            try
            {
                qs.NotifyJobListenersToBeExecuted(ctx);
            }
            catch (SchedulerException se)
            {
                qs.NotifySchedulerListenersError(
                    string.Format(CultureInfo.InvariantCulture, "Unable to notify JobListener(s) of Job to be executed: (Job will NOT be executed!). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);

                return(false);
            }

            return(true);
        }
Beispiel #38
0
 public void Execute(JobExecutionContext context)
 {
     ConsoleLog.WriteLog("定时修复订单:OrderRepaireJob...begin");
     try
     {
         //匿名账号
         //AuthorizeHelper.InitAuthorizeInfo();
         Jinher.AMP.BTP.ISV.Facade.CommodityOrderFacade facace = new ISV.Facade.CommodityOrderFacade();
         facace.RepairePickUpCode();
     }
     catch (Exception e)
     {
         ConsoleLog.WriteLog("Exception:" + e.Message, LogLevel.Error);
         ConsoleLog.WriteLog("Exception:" + e.StackTrace, LogLevel.Error);
     }
     ConsoleLog.WriteLog("定时修复订单:OrderRepaireJob end");
 }
		public void CreateRunnerAndExecuteJob_WithCallback()
		{
			JobExecutionContext context = new JobExecutionContext(
				Mocks.CreateMock<IScheduler>(), Mocks.CreateMock<ILogger>(),
				new JobSpec("job", "description", "key", Mocks.CreateMock<Trigger>()), null);

			IJobFactory jobFactory = Mocks.CreateMock<IJobFactory>();
			IJob job = Mocks.CreateMock<IJob>();

			Expect.Call(jobFactory.GetJob("key")).Return(job);
			Expect.Call(job.Execute(context)).Return(true);
			Expect.Call(delegate { jobFactory.ReleaseJob(null); }).IgnoreArguments();

			Mocks.ReplayAll();

			DefaultJobRunner runner = new DefaultJobRunner(jobFactory);

			IAsyncResult resultPassedToCallback = null;
			object barrier = new object();

			IAsyncResult asyncResult = runner.BeginExecute(context, delegate(IAsyncResult r)
			{
				resultPassedToCallback = r;

				lock (barrier)
					Monitor.PulseAll(barrier);
			}, "state");

			lock (barrier)
				if (resultPassedToCallback == null)
					Monitor.Wait(barrier, 10000);

			Assert.AreEqual("state", asyncResult.AsyncState);
			Assert.IsNotNull(asyncResult.AsyncWaitHandle);
			Assert.IsFalse(asyncResult.CompletedSynchronously);
			Assert.IsTrue(runner.EndExecute(asyncResult));
			Assert.IsTrue(asyncResult.IsCompleted);

			Assert.AreSame(asyncResult, resultPassedToCallback);
		}
		public void CreateRunnerAndExecuteJob_NoCallback()
		{
			JobExecutionContext context = new JobExecutionContext(
				Mocks.CreateMock<IScheduler>(), Mocks.CreateMock<ILogger>(),
				new JobSpec("job", "description", "key", Mocks.CreateMock<Trigger>()), null);

			IJobFactory jobFactory = Mocks.CreateMock<IJobFactory>();
			IJob job = Mocks.CreateMock<IJob>();

			Expect.Call(jobFactory.GetJob("key")).Return(job);
			Expect.Call(job.Execute(context)).Return(true);
			Expect.Call(delegate { jobFactory.ReleaseJob(null); }).IgnoreArguments();

			Mocks.ReplayAll();

			DefaultJobRunner runner = new DefaultJobRunner(jobFactory);
			IAsyncResult asyncResult = runner.BeginExecute(context, null, "state");
			Assert.AreEqual("state", asyncResult.AsyncState);
			Assert.IsNotNull(asyncResult.AsyncWaitHandle);
			Assert.IsFalse(asyncResult.CompletedSynchronously);
			Assert.IsTrue(runner.EndExecute(asyncResult));
			Assert.IsTrue(asyncResult.IsCompleted);
		}
Beispiel #41
0
 /// <summary>
 /// Gets the name of the process.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns>System.String.</returns>
 private static string GetProcessName(JobExecutionContext context)
 {
     return (string)context.JobDetail.JobDataMap["processName"];
 }
        public override void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException)
        {
            Key sj = (Key) chainLinks[context.JobDetail.Key];

            if (sj == null)
            {
                return;
            }

            Log.Info(string.Format(CultureInfo.InvariantCulture, "Job '{0}' will now chain to Job '{1}'", context.JobDetail.FullName, sj));

            try
            {
                if (context.JobDetail.Volatile || context.Trigger.Volatile)
                {
                    context.Scheduler.TriggerJobWithVolatileTrigger(sj.Name, sj.Group);
                }
                else
                {
                    context.Scheduler.TriggerJob(sj.Name, sj.Group);
                }
            }
            catch (SchedulerException se)
            {
                Log.Error(string.Format(CultureInfo.InvariantCulture, "Error encountered during chaining to Job '{0}'", sj), se);
            }
        }
		public void WrapsJobFactoryException()
		{
			JobExecutionContext context = new JobExecutionContext(
				Mocks.CreateMock<IScheduler>(), Mocks.CreateMock<ILogger>(),
				new JobSpec("job", "description", "key", Mocks.CreateMock<Trigger>()), null);

			IJobFactory jobFactory = Mocks.CreateMock<IJobFactory>();
			Expect.Call(jobFactory.GetJob("key")).Throw(new Exception("Ack!"));
			Mocks.ReplayAll();

			DefaultJobRunner jobRunner = new DefaultJobRunner(jobFactory);

			jobRunner.BeginExecute(context, null, null);
		}
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="Trigger" />
        /// has fired, it's associated <see cref="JobDetail" />
        /// has been executed, and it's <see cref="Trigger.Triggered" /> method has been
        /// called.
        /// </summary>
        /// <param name="trigger">The <see cref="Trigger" /> that was fired.</param>
        /// <param name="context">The <see cref="JobExecutionContext" /> that was passed to the
        /// <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
        /// <param name="triggerInstructionCode">The result of the call on the <see cref="Trigger" />'s <see cref="Trigger.Triggered" />  method.</param>
        public virtual void TriggerComplete(Trigger trigger, JobExecutionContext context, SchedulerInstruction triggerInstructionCode)
        {
            if (!Log.IsInfoEnabled)
            {
                return;
            }

            String instrCode = "UNKNOWN";
            if (triggerInstructionCode == SchedulerInstruction.DeleteTrigger)
            {
                instrCode = "DELETE TRIGGER";
            }
            else if (triggerInstructionCode == SchedulerInstruction.NoInstruction)
            {
                instrCode = "DO NOTHING";
            }
            else if (triggerInstructionCode == SchedulerInstruction.ReExecuteJob)
            {
                instrCode = "RE-EXECUTE JOB";
            }
            else if (triggerInstructionCode ==SchedulerInstruction.SetAllJobTriggersComplete)
            {
                instrCode = "SET ALL OF JOB'S TRIGGERS COMPLETE";
            }
            else if (triggerInstructionCode == SchedulerInstruction.SetTriggerComplete)
            {
                instrCode = "SET THIS TRIGGER COMPLETE";
            }

            object[] args =
                new object[]
                    {
                        trigger.Name, trigger.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), DateTime.UtcNow,
                        context.JobDetail.Name, context.JobDetail.Group, context.RefireCount, triggerInstructionCode, instrCode
                    };

            Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerCompleteMessage, args));
        }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="Trigger" />
        /// has fired, and it's associated <see cref="JobDetail" />
        /// is about to be executed.
        /// <p>
        /// It is called before the <see cref="VetoJobExecution" /> method of this
        /// interface.
        /// </p>
        /// </summary>
        /// <param name="trigger">The <see cref="Trigger" /> that has fired.</param>
        /// <param name="context">The <see cref="JobExecutionContext" /> that will be passed to the <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
        public virtual void TriggerFired(Trigger trigger, JobExecutionContext context)
        {
            if (!Log.IsInfoEnabled)
            {
                return;
            }

            object[] args =
                new object[]
                    {
                        trigger.Name, trigger.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), DateTime.UtcNow,
                        context.JobDetail.Name, context.JobDetail.Group, context.RefireCount
                    };

            Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerFiredMessage, args));
        }
 public virtual void TriggerComplete(Trigger trigger, JobExecutionContext context, SchedulerInstruction triggerInstructionCode)
 {
 }
Beispiel #47
0
		/// <summary>
		/// Passivates this instance.
		/// </summary>
		public virtual void Passivate()
		{
			jec = null;
			qs = null;
		}
Beispiel #48
0
        /// <summary>
        /// Gets the name of the schedule.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>System.String.</returns>
        private static string GetScheduleName(JobExecutionContext context)
        {
            if (context.Trigger != null)
            {
                if (QuartzScheduler.ManualTriggerGroupName.Equals(context.Trigger.Group, StringComparison.OrdinalIgnoreCase))
                    return "On demand";

                var trigger = context.Trigger as ESyncTrigger;

                if (trigger != null && trigger.Schedule != null)
                    return trigger.Schedule.Name;
            }

            return string.Empty;
        }
 public virtual bool VetoJobExecution(Trigger trigger, JobExecutionContext context)
 {
     return false;
 }
Beispiel #50
0
		private bool NotifyJobListenersComplete(JobExecutionContext ctx, JobExecutionException jobExEx)
		{
			try
			{
				qs.NotifyJobListenersWasExecuted(ctx, jobExEx);
			}
			catch (SchedulerException se)
			{
				qs.NotifySchedulerListenersError(
					string.Format(CultureInfo.InvariantCulture, "Unable to notify JobListener(s) of Job that was executed: (error will be ignored). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);

				return false;
			}

			return true;
		}
Beispiel #51
0
		private bool NotifyListenersBeginning(JobExecutionContext ctx)
		{
			bool vetoed;

			// notify all trigger listeners
			try
			{
				vetoed = qs.NotifyTriggerListenersFired(ctx);
			}
			catch (SchedulerException se)
			{
				qs.NotifySchedulerListenersError(
					string.Format(CultureInfo.InvariantCulture, "Unable to notify TriggerListener(s) while firing trigger (Trigger and Job will NOT be fired!). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);

				return false;
			}

			if (vetoed)
			{
				try
				{
					qs.NotifyJobListenersWasVetoed(ctx);
				}
				catch (SchedulerException se)
				{
					qs.NotifySchedulerListenersError(
						string.Format(CultureInfo.InvariantCulture, "Unable to notify JobListener(s) of vetoed execution while firing trigger (Trigger and Job will NOT be fired!). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);
				}
				throw new VetoedException(this);
			}

			// notify all job listeners
			try
			{
				qs.NotifyJobListenersToBeExecuted(ctx);
			}
			catch (SchedulerException se)
			{
				qs.NotifySchedulerListenersError(
					string.Format(CultureInfo.InvariantCulture, "Unable to notify JobListener(s) of Job to be executed: (Job will NOT be executed!). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);

				return false;
			}

			return true;
		}
 public void JobData_GetterAndSetter()
 {
     JobExecutionContext context = new JobExecutionContext(scheduler, logger, jobSpec, jobData);
     context.JobData = null;
     Assert.IsNull(context.JobData);
 }
Beispiel #53
0
 /// <summary>
 /// Gets the job unique identifier.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns>Guid.</returns>
 private static Guid GetJobGuid(JobExecutionContext context)
 {
     return (Guid)context.JobDetail.JobDataMap["syncProcessGuid"];
 }
Beispiel #54
0
        /// <summary>
        /// Gets the process synchronizer.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>IProcessSynchronizer.</returns>
        private IProcessSynchronizer GetProcessSynchronizer(JobExecutionContext context)
        {
            var processName = GetProcessName(context);
            var syncProcessGuid = GetJobGuid(context);

            return GetProcessSynchronizer(processName, syncProcessGuid);
        }
Beispiel #55
0
		/// <summary>
		/// Initializes the job execution context with given scheduler and bundle.
		/// </summary>
		/// <param name="sched">The scheduler.</param>
		/// <param name="firedBundle">The bundle offired triggers.</param>
		public virtual void Initialize(SchedulerScheduler sched, TriggerFiredBundle firedBundle)
		{
			qs = sched;

			IJob job;
			JobDetail jobDetail = firedBundle.JobDetail;

			try
			{
				job = sched.JobFactory.NewJob(firedBundle);
			}
			catch (SchedulerException se)
			{
				sched.NotifySchedulerListenersError(string.Format(CultureInfo.InvariantCulture, "An error occured instantiating job to be executed. job= '{0}'", jobDetail.FullName), se);
				throw;
			}
			catch (Exception e)
			{
				SchedulerException se = new SchedulerException(string.Format(CultureInfo.InvariantCulture, "Problem instantiating type '{0}'", jobDetail.JobType.FullName), e);
				sched.NotifySchedulerListenersError(string.Format(CultureInfo.InvariantCulture, "An error occured instantiating job to be executed. job= '{0}'", jobDetail.FullName), se);
				throw se;
			}

			jec = new JobExecutionContext(scheduler, firedBundle, job);
		}
Beispiel #56
0
		private bool NotifyTriggerListenersComplete(JobExecutionContext ctx, SchedulerInstruction instCode)
		{
			try
			{
				qs.NotifyTriggerListenersComplete(ctx, instCode);
			}
			catch (SchedulerException se)
			{
				qs.NotifySchedulerListenersError(
					string.Format(CultureInfo.InvariantCulture, "Unable to notify TriggerListener(s) of Job that was executed: (error will be ignored). trigger= {0} job= {1}", ctx.Trigger.FullName, ctx.JobDetail.FullName), se);

				return false;
			}

			if (!ctx.Trigger.GetNextFireTimeUtc().HasValue)
			{
				qs.NotifySchedulerListenersFinalized(ctx.Trigger);
			}

			return true;
		}
 /// <summary>
 /// Called by the <see cref="IScheduler"/> after a <see cref="JobDetail"/>
 /// has been executed, and be for the associated <see cref="Trigger"/>'s
 /// <see cref="Trigger.Triggered"/> method has been called.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="jobException"></param>
 public virtual void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException)
 {
 }
 public virtual void TriggerFired(Trigger trigger, JobExecutionContext context)
 {
 }
Beispiel #59
0
        /// <summary>
        /// Creates the e synchronize session.
        /// </summary>
        /// <param name="startTime">The start time.</param>
        /// <param name="context">The context.</param>
        /// <returns>IESyncSession.</returns>
        private IESyncSession CreateESyncSession(
            DateTime startTime,
            JobExecutionContext context)
        {
            try
            {
                var processName = GetProcessName(context);
                var jobGuid = GetJobGuid(context);
                var job = GetProcessSynchronizer(processName, jobGuid);

                var newSession = DynamicTypeManager.NewEditableRoot<IESyncSession>(Constants.ESyncSessionProcessName);
                newSession.AllowLazyLoading = true;
                newSession.StartTime = startTime;
                newSession.SynchronizedProcess = GetProcessDisplayName(processName);
                newSession.SynchronizedProcessName = processName;
                newSession.SyncProcessGuid = jobGuid.ToString();
                newSession.SynchronizationProcess = job.Name;
                newSession.Schedule = GetScheduleName(context);
                newSession = (IESyncSession)((ISavable)newSession).Save();

                if (newSession.Id > 0)
                    return newSession;
            }
            catch (Exception ex)
            {
                Logger.Log(LogSeverity.Error, "ESYNC", ex);
            }

            return null;
        }
Beispiel #60
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <exception cref="System.InvalidOperationException">No key fields were specified.</exception>
        public void Execute(JobExecutionContext context)
        {
            var startTime = DateTime.Now;

            Ioc.SatisfyImportsOnce(this);

            var processName = string.Empty;

            try
            {
                processName = GetProcessName(context);
                var isSuccessful = true;

                Logger.Log(
                    LogSeverity.Information,
                    "ESYNC",
                    string.Format(CultureInfo.InvariantCulture, "Process \"{0}\" synchronization started.", processName));

                var synchronizer = GetProcessSynchronizer(context);
                var session = CreateESyncSession(startTime, context);

                try
                {
                    var filterBuilders = CreateKeyFilterBuilders(synchronizer);
                    if (filterBuilders.Count == 0)
                        throw new InvalidOperationException("No key fields were specified.");

                    var fieldUpdaters = CreateFieldUpdaters(synchronizer);

                    var dpContext = new DataProviderContext();
                    var lastSuccessfulSession = GetLastSuccessfulSession(synchronizer);
                    if (lastSuccessfulSession != null)
                        dpContext.LastSuccessDate = lastSuccessfulSession.EndTime;

                    var data = GetData(synchronizer.DataProvider, dpContext);

                    session = LogItemsRetrieved(session, data.Count);

                    for (var i = 0; i < data.Count; ++i)
                    {
                        if (SyncServiceJob.IsStopped)
                        {
                            isSuccessful = false;
                            LogError(session, "The synchronization session was stopped.");
                            break;
                        }

                        var item = data[i];
                        var syncContext = new SynchronizationContext();

                        try
                        {
                            var result = Synchronize(synchronizer, filterBuilders, fieldUpdaters, item, syncContext);

                            isSuccessful = isSuccessful && result;

                            if (!result || syncContext.Errors.Count > 0 || syncContext.Warnings.Count > 0)
                            {
                                var description = GetDescription(syncContext);

                                Logger.Log(
                                    LogSeverity.Error,
                                    "ESYNC",
                                    string.Format(
                                        CultureInfo.InvariantCulture,
                                        "Synchronization failed for process \"{0}\", record {1}:{2}{3}",
                                        processName,
                                        i + 1,
                                        Environment.NewLine,
                                        description));

                                LogError(
                                    session,
                                    string.Format(CultureInfo.InvariantCulture, "Failed to synchronize record {0}.", i + 1),
                                    description,
                                    item);
                            }
                        }
                        catch (Exception ex)
                        {
                            isSuccessful = false;

                            Logger.Log(LogSeverity.Error, "ESYNC", ex);
                            LogError(session, string.Format(CultureInfo.InvariantCulture, "Failed to synchronize record {0}.", i + 1), ex.ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    isSuccessful = false;
                    Logger.Log(LogSeverity.Error, "ESYNC", ex);
                    LogError(session, ex.Message, ex.ToString());
                }

                if (session != null)
                {
                    session.EndTime = DateTime.Now;
                    session.IsSuccessful = isSuccessful;
                    ((ISavable)session).Save();
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogSeverity.Error, GetType().ToString(), ex);
            }
            finally
            {
                //Csla.ApplicationContext.User = new UnauthenticatedPrincipal();
                Logger.Log(LogSeverity.Information, "ESYNC", string.Format(CultureInfo.InvariantCulture, "Process \"{0}\" synchronization finished.", processName));
            }
        }