public JobDefinition(string jobKey, Func<Task> factory, IJobSchedule schedule = null, string description = null)
 {
     _jobKey = jobKey;
     _factory = factory;
     _schedule = schedule;
     _description = description;
 }
        public static Quartz.Collection.ISet <ITrigger> BuildTriggers(IJobSchedule schedule)
        {
            if (schedule == null || schedule.Triggers == null)
            {
                return(null);
            }

            var errors = new List <string>();
            var set    = new Quartz.Collection.HashSet <ITrigger>(schedule.Triggers.Select(t =>
            {
                try
                {
                    return(ParseTrigger(t));
                }
                catch (Exception ex)
                {
                    errors.Add(ex.Message);
                    return(null);
                }
            }).Where(t => t != null));

            if (errors.Count > 0)
            {
                Log.Error("Trigger Creation Errors: \n" + string.Join("\n", errors));
            }
            return(set);
        }
 public JobDefinition(string jobKey, Func <Task> factory, IJobSchedule schedule = null, string description = null)
 {
     _jobKey      = jobKey;
     _factory     = factory;
     _schedule    = schedule;
     _description = description;
 }
Example #4
0
        /// <summary>
        /// Adds the task.
        /// </summary>
        /// <typeparam name="TTransportInit">The type of the transport initialize.</typeparam>
        /// <param name="jobQueueCreation">The job queue creation.</param>
        /// <param name="name">The name.</param>
        /// <param name="queueConnection">Queue and connection information.</param>
        /// <param name="schedule">The schedule.</param>
        /// <param name="autoRun">if set to <c>true</c> [automatic run].</param>
        /// <param name="window">The window.</param>
        /// <param name="actionToRun">The action to run.</param>
        /// <param name="expressionToRun">The expression to run.</param>
        /// <param name="route">The route.</param>
        /// <param name="rawExpression">if set to <c>true</c> this expression will not be serialized. This will fail unless an in-process queue is being used.</param>
        /// <param name="producerConfiguration">The producer configuration.</param>
        /// <returns></returns>
        /// <exception cref="JobSchedulerException">Cannot add a task after Shutdown has been called.</exception>
        private ScheduledJob AddTaskImpl <TTransportInit>(
            IJobQueueCreation jobQueueCreation,
            string name,
            QueueConnection queueConnection,
            IJobSchedule schedule,
            bool autoRun,
            TimeSpan window,
            Expression <Action <IReceivedMessage <MessageExpression>, IWorkerNotification> > actionToRun,
            LinqExpressionToRun expressionToRun,
            string route,
            bool rawExpression,
            Action <QueueProducerConfiguration> producerConfiguration = null)
            where TTransportInit : ITransportInit, new()
        {
            Guard.NotNull(() => schedule, schedule);
            Guard.NotNullOrEmpty(() => name, name);

            ScheduledJob job;

            lock (_lockTasks)
            {
                if (IsShuttingDown)
                {
                    throw new JobSchedulerException("Cannot add a task after Shutdown has been called.");
                }

                if (_tasks.ContainsKey(name))
                {
                    RemoveJob(name);
                }
                if (expressionToRun != null)
                {
                    job = new ScheduledJob(this, name, schedule, _jobQueue.Get <TTransportInit>(jobQueueCreation, queueConnection, producerConfiguration), expressionToRun, _getTime.Create(), route)
                    {
                        Window     = window,
                        IsAttached = true
                    };
                    _tasks.Add(name, job);
                }
                else
                {
                    job = new ScheduledJob(this, name, schedule, _jobQueue.Get <TTransportInit>(jobQueueCreation, queueConnection, producerConfiguration), actionToRun, _getTime.Create(), route, rawExpression)
                    {
                        Window     = window,
                        IsAttached = true
                    };
                    _tasks.Add(name, job);
                }
            }

            job.OnException += TaskOnOnException;
            job.OnEnQueue   += JobOnOnEnQueue;
            job.OnNonFatalFailureEnQueue += JobOnOnNonFatalFailureEnQueue;
            if (autoRun)
            {
                job.StartSchedule();
            }

            return(job);
        }
Example #5
0
        /// <summary>
        /// Returns true if the job schedule applies at <paramref name="refDate"/> given the <paramref name="lastRun"/>
        /// </summary>
        /// <param name="me">The job schedule to determine applicability</param>
        /// <param name="refDate">The time that the system is checking if the job execution applies</param>
        /// <param name="lastRun">The last known run time / check time of the job. Null if never run</param>
        /// <returns>True if the schedule applies</returns>
        public static bool AppliesTo(this IJobSchedule me, DateTime refDate, DateTime?lastRun)
        {
            var retVal = refDate >= me.StartTime;                           // The reference date is in valid bounds for start

            retVal &= !me.StopTime.HasValue || refDate < me.StopTime.Value; // The reference date is in valid bounds of stop (if specified)

            // Are there week days specified
            if (me.Type == Configuration.JobScheduleType.Interval && (!lastRun.HasValue || refDate.Subtract(lastRun.Value) > me.Interval))
            {
                return(true);
            }
            else if (me.Type == Configuration.JobScheduleType.Scheduled)
            {
                if (me.Days != null && me.Days.Any())
                {
                    retVal &= me.Days.Any(r => r == refDate.DayOfWeek) &&
                              refDate.Hour >= me.StartTime.Hour &&
                              refDate.Minute >= me.StartTime.Minute &&
                              refDate.Date > me.StartTime;
                    retVal &= !lastRun.HasValue ? DateTime.Now.Hour == me.StartTime.Hour : (lastRun.Value.Date < refDate.Date); // Last run does not cover this calculation - i.e. have we not already run this repeat?
                }
                else // This is an exact time
                {
                    retVal &= refDate.Date == me.StartTime.Date &&
                              refDate.Hour >= me.StartTime.Hour &&
                              refDate.Minute >= me.StartTime.Minute &&
                              !lastRun.HasValue;
                }
            }

            return(retVal);
        }
        public int CompareTo(IJobSchedule other)
        {
            if (this.Identifier == other.Identifier)
            {
                return(0);
            }

            IEnumerable <Type> thisTypes  = this.Triggers.Where(t => t.Type == ScheduleType.DependentOnOther).Select(t => t.DependentOnType),
                               otherTypes = other.Triggers.Where(t => t.Type == ScheduleType.DependentOnOther).Select(t => t.DependentOnType);

            if (thisTypes.Contains(other.Type))
            {
                return(1);
            }
            if (otherTypes.Contains(this.Type))
            {
                return(-1);
            }
            if (otherTypes.Count() > 0)
            {
                return(-1);
            }
            if (thisTypes.Count() > 0)
            {
                return(1);
            }

            return(this.JobScheduleID.CompareTo(other.Identifier));
        }
Example #7
0
 private static ITrigger createTrigger(IJobSchedule jobSchedule)
 => TriggerBuilder
 .Create()
 .WithIdentity($"{jobSchedule.JobType.FullName}.trigger")
 .WithCronSchedule(jobSchedule.CronExpression)
 .WithDescription(jobSchedule.CronExpression)
 .Build();
 public void SetUp()
 {
     _job          = Mock.Of <IJob>();
     _jobSchedule  = Mock.Of <IJobSchedule>();
     _timeProvider = Mock.Of <ITimeProvider>();
     _jobScheduler = new JobScheduler(_jobSchedule, _job, _timeProvider);
 }
Example #9
0
        /// <inheritdoc/>
        public void Add(IJob job, IJobSchedule jobSchedule)
        {
            lock (this.m_lock)
            {
                var scheduleReg = this.m_jobSchedules.Find(o => o.Type == job.GetType());
                if (scheduleReg == null)
                {
                    scheduleReg = new JobItemConfiguration()
                    {
                        Type = job.GetType(), Schedule = new List <JobItemSchedule>()
                    };
                    this.m_jobSchedules.Add(scheduleReg);
                }
                scheduleReg.Schedule.Add(new JobItemSchedule()
                {
                    Type              = jobSchedule.Type,
                    Interval          = (int)jobSchedule.Interval.GetValueOrDefault().TotalSeconds,
                    IntervalSpecified = jobSchedule.Interval.HasValue,
                    RepeatOn          = jobSchedule.Days,
                    StartDate         = jobSchedule.StartTime,
                    StopDate          = jobSchedule.StopTime.GetValueOrDefault(),
                    StopDateSpecified = jobSchedule.StopTime.HasValue
                });

                this.SaveCron();
            }
        }
Example #10
0
        private bool IsRunning(IJobSchedule sche)
        {
            if (sche.LastStartDt == null)
            {
                return(false);
            }

            return((sche.LastStartDt.Value < DateTime.Now) && (sche.LastEndDt == null));
        }
Example #11
0
        private string GetJobStatus(IJobSchedule sch)
        {
            if (IsRunning(sch))
            {
                return("Probíhá");
            }

            return((sch.LastRunFailed ?? false) ? "Selhal" : "OK");
        }
Example #12
0
 private static ITrigger CreateTrigger(IJobSchedule schedule)
 {
     return(TriggerBuilder
            .Create()
            .WithIdentity($"{schedule.JobType.FullName}.trigger")
            .WithCronSchedule(schedule.CronExpression)
            .WithDescription(schedule.CronExpression)
            .Build());
 }
Example #13
0
        public void MarkJobFailed(IJobSchedule job)
        {
            m_log.Info($"MarkJobFailed called {job?.Uid}");

            job.LastEndDt     = DateTime.Now;
            job.LastRunFailed = true;
            m_database.Save(job);

            m_log.Info($"MarkJobSucceeded OK {job?.Uid}");
        }
Example #14
0
 /// <summary>
 /// Job scheduling information
 /// </summary>
 public JobScheduleInfo(IJobSchedule schedule)
 {
     this.Type                 = schedule.Type;
     this.Interval             = schedule.Interval.GetValueOrDefault();
     this.IntervalXmlSpecified = schedule.Interval.HasValue;
     this.StartDate            = schedule.StartTime;
     this.StopDate             = schedule.StopTime.GetValueOrDefault();
     this.StopDateSpecified    = schedule.StopTime.HasValue;
     this.RepeatOn             = schedule.Days;
 }
 public static JobBuilder GetJobBuilder(IJobSchedule schedule, bool durable = true)
 {
     return(JobBuilder.Create(schedule.Type)
            .WithIdentity(schedule.Identifier, Helper.GetJobGroupName(schedule))
            .StoreDurably(durability: durable)
            .UsingJobData(new JobDataMap(new Dictionary <string, object>
     {
         { "ConnectionString", ConfigurationManager.ConnectionStrings["connectionString"] }
     } as IDictionary <string, object>)));
 }
Example #16
0
        private static IJobDetail CreateJob(IJobSchedule schedule)
        {
            var jobType = schedule.JobType;

            return(JobBuilder
                   .Create(jobType)
                   .WithIdentity(jobType.FullName)
                   .WithDescription(jobType.Name)
                   .Build());
        }
Example #17
0
        public void MarkJobStarted(IJobSchedule job)
        {
            m_log.Info($"MarkJobStarted called {job?.Uid}");

            job.LastEndDt   = null;
            job.LastStartDt = DateTime.Now;

            m_database.Save(job);

            m_log.Info($"MarkJobStarted OK {job?.Uid}");
        }
Example #18
0
        private static bool IsRetryTime(IJobSchedule schedule)
        {
            if (schedule.RetryMinutes == null)
            {
                return(true);
            }

            var retryTime = schedule.LastStartDt ?? DateTime.MinValue;

            retryTime = retryTime.AddMinutes(schedule.RetryMinutes ?? 0);

            return(retryTime <= DateTime.Now);
        }
        public JobScheduler(IJobSchedule jobSchedule, IJob job, ITimeProvider timeProvider)
        {
            _logger.Info("JobScheduler constructor was called");

            _jobSchedule  = jobSchedule ?? throw new ArgumentNullException(nameof(jobSchedule));
            _job          = job ?? throw new ArgumentNullException(nameof(job));
            _timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));

            _schedulerThread = new Thread(SchedulerThread)
            {
                IsBackground = true
            };
        }
Example #20
0
 internal ScheduledJob(JobScheduler scheduler,
     string name,
     IJobSchedule schedule,
     IProducerMethodJobQueue queue,
     Expression<Action<IReceivedMessage<MessageExpression>, IWorkerNotification>> actionToRun,
     IGetTime time,
     string route)
 {
     _scheduler = scheduler;
     Name = name;
     Schedule = schedule;
     _queue = queue;
     _actionToRun = actionToRun;
     _getTime = time;
     Route = route;
 }
Example #21
0
 internal ScheduledJob(JobScheduler scheduler,
                       string name,
                       IJobSchedule schedule,
                       IProducerMethodJobQueue queue,
                       LinqExpressionToRun expressionToRun,
                       IGetTime time,
                       string route
                       )
 {
     _scheduler       = scheduler;
     Name             = name;
     Schedule         = schedule;
     _queue           = queue;
     _expressionToRun = expressionToRun;
     _getTime         = time;
     Route            = route;
 }
Example #22
0
        public IJobSchedule[] GetJobSchedules()
        {
            var dictionary = new Dictionary <string, Type>();

            dictionary.Add("EmptyTask", typeof(EmptyTask));
            var jobScheduler = ContextFactory.Current.ResolveDependency <IJobScheduler>();

            jobScheduler.RegisterTaskFactory(dictionary);

            var schedule = new IJobSchedule[1];

            schedule[0]            = ContextFactory.Current.ResolveDependency <IJobSchedule>();
            schedule[0].Name       = "EmptyTask";
            schedule[0].EveryAfter = 30;
            schedule[0].Type       = SchedulerEventType.EveryAfter;
            return(schedule);
        }
Example #23
0
 internal ScheduledJob(JobScheduler scheduler,
     string name,
     IJobSchedule schedule,
     IProducerMethodJobQueue queue,
     LinqExpressionToRun expressionToRun,
     IGetTime time,
     string route
    )
 {
     _scheduler = scheduler;
     Name = name;
     Schedule = schedule;
     _queue = queue;
     _expressionToRun = expressionToRun;
     _getTime = time;
     Route = route;
 }
Example #24
0
 internal ScheduledJob(JobScheduler scheduler,
                       string name,
                       IJobSchedule schedule,
                       IProducerMethodJobQueue queue,
                       Expression <Action <IReceivedMessage <MessageExpression>, IWorkerNotification> > actionToRun,
                       IGetTime time,
                       string route,
                       bool rawExpression)
 {
     _scheduler    = scheduler;
     Name          = name;
     Schedule      = schedule;
     _queue        = queue;
     _actionToRun  = actionToRun;
     _getTime      = time;
     Route         = route;
     RawExpression = rawExpression;
 }
Example #25
0
 private string GetStartMode(IJobSchedule sch)
 {
     if (sch.Active)
     {
         if (sch.CanBeStartedManually)
         {
             return("Automaticky nebo ručně");
         }
         else
         {
             return("Pouze automaticky");
         }
     }
     else
     {
         return("Pouze ručně");
     }
 }
Example #26
0
        /// <summary>Returns a matching date-time for a given schedule after certain time.</summary>
        /// <param name="schedule">Job schedule entity.</param>
        /// <param name="afterDate">Start date to search for matching date.</param>
        /// <returns>Date-time of the next matching date. Returns null if no match - the date is outside the schedule&quot;s active period.</returns>
        public static DateTime?GetNextStartAfter(this IJobSchedule schedule, DateTime afterDate)
        {
            if (schedule.ActiveUntil != null && afterDate > schedule.ActiveUntil.Value)
            {
                return(null);
            }
            if (afterDate < schedule.ActiveFrom)
            {
                afterDate = schedule.ActiveFrom;
            }
            var cron   = new Cron.CronSchedule(schedule.CronSpec);
            var result = cron.TryGetNext(afterDate);

            if (result != null && schedule.ActiveUntil != null && result.Value > schedule.ActiveUntil.Value)
            {
                result = null;
            }
            return(result);
        }
Example #27
0
        public void UpdateSchedule(IJobSchedule schedule)
        {
            Guard.NotNull(() => schedule, schedule);
            lock (_scheduleLock)
            {
                var wasRunning = IsScheduleRunning;
                if (wasRunning)
                {
                    StopSchedule();
                }

                Schedule = schedule;

                if (wasRunning)
                {
                    StartSchedule();
                }
            }
        }
        private void OnJobScheduleSaving(IJobSchedule sched)
        {
            var     session   = EntityHelper.GetSession(sched);
            var     job       = sched.Job;
            var     utcNow    = session.Context.App.TimeService.UtcNow;
            var     nextRunId = sched.NextRunId;
            IJobRun nextRun   = (nextRunId == null) ? null : session.GetEntity <IJobRun>(nextRunId.Value);

            switch (sched.Status)
            {
            case JobScheduleStatus.Stopped:
                // if there is a pending run in the future, kill it
                if (nextRun != null && nextRun.Status == JobRunStatus.Pending && nextRun.StartOn > utcNow.AddMinutes(1))
                {
                    nextRun.Status = JobRunStatus.Killed;
                }
                break;

            case JobScheduleStatus.Active:
                // Create or adjust JobRun entity for next run
                var nextStartOn = sched.GetNextStartAfter(utcNow);
                if (nextStartOn != null)
                {
                    if (nextRun == null || nextRun.Status != JobRunStatus.Pending)
                    {
                        nextRun         = NewJobRun(job, JobRunType.Schedule, nextStartOn, hostName: sched.HostName);
                        sched.NextRunId = nextRun.Id;
                    }
                    else
                    {
                        nextRun.StartOn = nextStartOn.Value;
                    }
                }
                else
                {
                    //nextSTartOn == null
                    sched.NextRunId = null;
                }
                break;
            } //switch
        }     //method
Example #29
0
        public void LaunchJob(IJobSchedule jobEntry)
        {
            IExecutableJob jobExecutable = null;

            try
            {
                m_log.Info($"Vytvarim instanci {jobEntry.ScheduledJob.ModuleClass}");
                jobExecutable = m_serviceLocator.InstantiateNow <IExecutableJob>(jobEntry.ScheduledJob.ModuleClass);

                if (jobExecutable == null)
                {
                    throw new InvalidOperationException("Cannot instantiate the job");
                }

                m_log.Info($"Job instance created {jobExecutable}");
            }
            catch (Exception ex)
            {
                m_log.Error("Job instantiation failed", ex);
                return;
            }

            m_scheduledJobs.MarkJobStarted(jobEntry);

            try
            {
                m_log.Info("Spoustim job");
                jobExecutable.Run(jobEntry.ScheduledJob.CustomData);

                m_log.Info("Job uspesne dokoncen");
                m_scheduledJobs.MarkJobSucceeded(jobEntry);
            }
            catch (Exception ex)
            {
                m_log.Error("Job selhal", ex);
                m_scheduledJobs.MarkJobFailed(jobEntry);
            }
        }
Example #30
0
        public void UpdateSchedule(IJobSchedule schedule)
        {
            Guard.NotNull(() => schedule, schedule);
            lock (_scheduleLock)
            {
                var wasRunning = IsScheduleRunning;
                if (wasRunning)
                    StopSchedule();

                Schedule = schedule;

                if (wasRunning)
                    StartSchedule();
            }
        }
 public static IJobDetail CreateJob(IJobSchedule schedule, bool durable = true)
 {
     return(GetJobBuilder(schedule, durable: durable).Build());
 }
 public static string GetJobGroupName(IJobSchedule schedule)
 {
     return(schedule.Type.FullName);
 }
Example #33
0
 public int CompareTo(IJobSchedule other)
 {
     return(NextStartTime.CompareTo(other.NextStartTime));
 }
 public static JobDefinition Schedule(string jobKey, Func<Task> factory, IJobSchedule schedule, string description = null)
 {
     return new JobDefinition(jobKey, factory, schedule, description);
 }
 public static JobDefinition Schedule(string jobKey, Action exe, IJobSchedule schedule, string description = null)
 {
     Func<Task> factory = () => Task.Factory.StartNew(exe);
     return new JobDefinition(jobKey, factory, schedule, description);
 }
 public static JobDefinition Schedule(string jobKey, Func <Task> factory, IJobSchedule schedule, string description = null)
 {
     return(new JobDefinition(jobKey, factory, schedule, description));
 }