示例#1
0
        public async Task <ScheduledJob> FindAciveJobAsync(ScheduledJobType jobType)
        {
            using (var scope = _container.BeginLifetimeScope())
            {
                var repository = scope.Resolve <IScheduledJobRepository>();
                await repository.CancelExpiredJobsAsync(jobType);

                ScheduledJob existingJob = null;
                var          jobs        = await repository.GetActiveJobsAsync(jobType);

                if (jobs != null && jobs.Any())
                {
                    existingJob = jobs.OrderByDescending(j => j.StartDate).First();
                    foreach (var job in jobs)
                    {
                        if (job.JobId != existingJob.JobId)
                        {
                            job.Status        = JobStatus.Cancelled;
                            job.CompletedDate = DateTime.UtcNow;

                            repository.Commit();
                        }
                    }
                }

                return(existingJob);
            }
        }
示例#2
0
        private async Task ScheduleJobInternalAsync(ScheduledJob job, bool execStartup, bool execReboot)
        {
            if (job == null)
            {
                throw new ArgumentNullException(nameof(job));
            }

            if (!(job.Enabled ?? true))
            {
                return;
            }

            if (string.IsNullOrEmpty(job.Name))
            {
                m_Logger.LogError($"Job of type {job.Task} has no name set.");
                return;
            }

            if (string.IsNullOrEmpty(job.Task))
            {
                m_Logger.LogError($"Job \"{job.Name}\" has no task set.");
                return;
            }

            if (string.IsNullOrEmpty(job.Schedule))
            {
                m_Logger.LogError($"Job \"{job.Name}\" has no schedule set.");
                return;
            }

            if (job.Schedule !.Equals("@single_exec", StringComparison.OrdinalIgnoreCase))
            {
                await ExecuteJobAsync(job);
                await RemoveJobAsync(job);

                return;
            }

            if (job.Schedule.Equals("@reboot", StringComparison.OrdinalIgnoreCase))
            {
                if (execReboot)
                {
                    await ExecuteJobAsync(job);
                }

                return;
            }

            if (job.Schedule.Equals("@startup", StringComparison.OrdinalIgnoreCase))
            {
                if (execStartup)
                {
                    await ExecuteJobAsync(job);
                }

                return;
            }

            ScheduleCronJob(job);
        }
        // Token: 0x0600037C RID: 892 RVA: 0x000161F8 File Offset: 0x000143F8
        private Guid SubmitScheduledJobToScheduler(Guid jobId, ScheduledJob job, bool executeImmediately, bool useLocal)
        {
            Guid result;

            using (IJobSchedulerHelper jobSchedulerHelper = useLocal ? JobScheduler.GetLocalInstance() : JobScheduler.GetMainInstance())
            {
                if (jobId == Guid.Empty)
                {
                    OrionDiscoveryJobFactory.log.Debug("Adding new job to Job Engine");
                    result = jobSchedulerHelper.AddJob(job);
                }
                else
                {
                    try
                    {
                        OrionDiscoveryJobFactory.log.DebugFormat("Updating job definition in Job Engine ({0})", jobId);
                        jobSchedulerHelper.UpdateJob(jobId, job, executeImmediately);
                        return(jobId);
                    }
                    catch (FaultException <JobEngineConnectionFault> )
                    {
                        OrionDiscoveryJobFactory.log.DebugFormat("Unable to update job definition in Job Engine({0}", jobId);
                        throw;
                    }
                    catch (Exception)
                    {
                        OrionDiscoveryJobFactory.log.DebugFormat("Unable to update job definition in Job Engine({0}", jobId);
                    }
                    OrionDiscoveryJobFactory.log.Debug("Adding new job to Job Engine");
                    result = jobSchedulerHelper.AddJob(job);
                }
            }
            return(result);
        }
示例#4
0
        public void SetUp()
        {
            var rule = new StubbedScheduleRule();

            rule.ScheduledTimes[now] = theNextTimeAccordingToTheSchedulerRule;

            TheJobTracker.Stub(x => x.Now()).Return(now);

            var job = theJobIs();

            var scheduledJob = new ScheduledJob <RiggedJob>(rule);

            scheduledJob.Timeout = theConfiguredTimeout;
            theTask = scheduledJob.ToTask(job, TheJobTracker);

            try
            {
                theTask.Wait();
            }
            catch (Exception)
            {
                // okay to swallow because you'll
                // check it on task itself
            }
        }
示例#5
0
        private async Task ExecuteJobAsync(ScheduledJob job)
        {
            if (job == null)
            {
                throw new ArgumentNullException(nameof(job));
            }

            var jobExecutor = m_JobExecutors.FirstOrDefault(d => d.SupportsType(job.Task !));

            if (jobExecutor == null)
            {
                m_Logger.LogError($"[{job.Name}] Unknown job type: {job.Task}");
                return;
            }

            try
            {
                await jobExecutor.ExecuteAsync(new JobTask(job.Name !, job.Task !,
                                                           job.Args ?? new Dictionary <string, object?>()));
            }
            catch (Exception ex)
            {
                m_Logger.LogError(ex, $"Job \"{job.Name}\" generated an exception.");
            }
        }
示例#6
0
        public ScheduleWidget(BaseScene scene, PlaceSchedule schedule, JobOffer offerToPlan, bool enabled = true, bool isRescheduling = false, EmployeeState employeeToHighlight = null) : base()
        {
            this.employeeToHighlight = employeeToHighlight;
            this.isRescheduling      = isRescheduling;
            this.scene       = scene;
            this.schedule    = schedule;
            this.offerToPlan = offerToPlan;
            this.enabled     = enabled;
            bg              = ContentLoader.GetTexture("white");
            padlock         = ContentLoader.GetTexture("padlock");
            error           = ContentLoader.GetTexture("error");
            edit            = ContentLoader.GetTexture("edit");
            newScheduledJob = offerToPlan != null ? new ScheduledJob(offerToPlan) : null;

            if (isRescheduling)
            {
                foreach (var job in schedule.Jobs)
                {
                    if (job.Job.Id != offerToPlan.Id)
                    {
                        continue;
                    }
                    foreach (var time in job.ShipTimes)
                    {
                        lastModifiedShipDay = time.Key;
                        newScheduledJob.ShipTimes.Add(time.Key, new ShipTimeAssignment(time.Value.Time, time.Value.AssignedEmployee, time.Value.StayAtLocation));
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        protected override void ProcessRecord()
        {
            //WriteObject(ForensicTimeline.GetInstances(Prefetch.GetInstances(volume)), true);

            WriteVerbose("Getting ScheduledJob Instances");
            WriteObject(ForensicTimeline.GetInstances(ScheduledJob.GetInstances(volume)), true);

            WriteVerbose("Getting ShellLink Instances");
            WriteObject(ForensicTimeline.GetInstances(ShellLink.GetInstances(volume)), true);

            WriteVerbose("Getting FileRecord Instances");
            WriteObject(ForensicTimeline.GetInstances(FileRecord.GetInstances(volume)), true);

            WriteVerbose("Getting UsnJrnl Instances");
            WriteObject(ForensicTimeline.GetInstances(UsnJrnl.GetInstances(volume)), true);

            WriteVerbose("Getting EventRecord Instances");
            WriteObject(ForensicTimeline.GetInstances(EventRecord.GetInstances(volume)), true);

            WriteVerbose("Getting DRIVERS Hive Keys");
            WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\DRIVERS")), true);

            WriteVerbose("Getting SAM Hive Keys");
            WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SAM")), true);

            WriteVerbose("Getting SECURITY Hive Keys");
            WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SECURITY")), true);

            WriteVerbose("Getting SOFTWARE Hive Keys");
            WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SOFTWARE")), true);

            WriteVerbose("Getting SYSTEM Hive Keys");
            WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SYSTEM")), true);
        }
        public ActionResult Create(ScheduledJobViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var jobInfo = new JobInfoModel
                {
                    JobType        = "Scheduled",
                    CronExpression = vm.CronExpression,
                    Url            = vm.Url
                };

                var newScheduledJob = new ScheduledJob
                {
                    Name    = vm.Name,
                    JobInfo = JsonConvert.SerializeObject(jobInfo)
                };

                _db.ScheduledJobs.Add(newScheduledJob);
                _db.SaveChanges();

                try
                {
                    // Create Hangfire Job
                    RecurringJob.AddOrUpdate(vm.Name, () => WebClientHelper.InvokeUrl(vm.Url), vm.CronExpression);
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex) {
                    ViewBag.jobException = "Invalid cron expression";
                }
            }

            return(View(vm));
        }
 // Token: 0x06000339 RID: 825 RVA: 0x00014414 File Offset: 0x00012614
 public void UpdateJob(Guid jobId, ScheduledJob job, bool executeImmediately)
 {
     this.ExecuteJobSchedulerOperation <int>("UpdateJob", delegate()
     {
         this.schedulerChannel.UpdateJob(jobId, job, executeImmediately);
         return(0);
     });
 }
示例#10
0
            public ChannelExpression ScheduledBy(IScheduleRule rule)
            {
                var job = new ScheduledJob <TJob>(rule);

                _parent._parent.AlterSettings <ScheduledJobGraph>(x => x.Jobs.Add(job));

                return(new ChannelExpression(job));
            }
示例#11
0
 private Guid SubmitScheduledJobToScheduler(ScheduledJob job)
 {
     using (IJobSchedulerHelper ijobSchedulerHelper = this.jobSchedulerHelperFactory())
     {
         OneTimeJobManager.Logger.Debug((object)"Adding new job to Job Engine");
         return(((IJobScheduler)ijobSchedulerHelper).AddJob(job));
     }
 }
示例#12
0
 public void UpdateJob(Guid jobId, ScheduledJob job, bool executeImmediately)
 {
     this.ExecuteJobSchedulerOperation <int>(nameof(UpdateJob), (JobScheduler.JobSchedulerOperation <int>)(() =>
     {
         this.schedulerChannel.UpdateJob(jobId, job, executeImmediately);
         return(0);
     }));
 }
示例#13
0
        public void NeedsExecuting_With_Typed_Cron_Job_Is_True()
        {
            var christmas    = new DateTime(2020, 12, 25, 0, 0, 10, DateTimeKind.Utc);
            var scheduledJob = new ScheduledJob(typeof(MockCronJob));
            var next         = scheduledJob.NeedsExecuting(christmas);

            Assert.IsTrue(next ?? false);
        }
示例#14
0
        public void NeedsExecuting_With_Untyped_Cron_Job_Is_True()
        {
            var christmas    = new DateTime(2020, 12, 25, 0, 0, 10, DateTimeKind.Utc);
            var scheduledJob = new ScheduledJob("*/10 * * * * *", _dummyHandler, OverlapHandling.Allow);
            var next         = scheduledJob.NeedsExecuting(christmas);

            Assert.IsTrue(next ?? false);
        }
示例#15
0
 private static void ScheduleRunNow(ScheduledJob job, IScheduledJobRepository scheduledJobRepository)
 {
     job.IntervalType   = ScheduledIntervalType.None;
     job.IntervalLength = 0;
     job.IsEnabled      = true;
     job.NextExecution  = DateTime.Now.AddSeconds(10);
     scheduledJobRepository.Save(job);
 }
示例#16
0
 public void StopJob(ScheduledJob job)
 {
     if (_jobTimers.ContainsKey(job))
     {
         _jobTimers[job].Cancel();
         _jobTimers.Remove(job);
     }
 }
示例#17
0
 public ActiveJob(ScheduledJob job, ShipTimeAssignment assignment, DateTime shipTime, EmployeeState employee)
 {
     this.UsedTruck  = assignment.AssignedEmployee.AssignedTruck;
     this.Job        = job;
     this.Employee   = employee;
     this.ShipDate   = shipTime;
     this.Assignment = assignment;
     this.EndDate    = ShipDate.AddHours(job.Job.GetTravelTime());
 }
        public ScheduledJobRegistry()
        {
            EnableInMemoryTransport();

            ScheduledJob.DefaultJobChannel(x => x.Downstream);
            ScheduledJob.RunJob <AJob>().ScheduledBy <DummyScheduleRule>().Channel(x => x.Upstream);
            ScheduledJob.RunJob <BJob>().ScheduledBy <DummyScheduleRule>().Timeout(11.Minutes());
            ScheduledJob.RunJob <CJob>().ScheduledBy <DummyScheduleRule>();
        }
示例#19
0
        public static ScheduledJob GetJobDefinition()
        {
            ScheduledJobRepository repository =
                ServiceLocator.Current.GetInstance <ScheduledJobRepository>();
            ScheduledJob job = repository.Get("Execute", typeof(SendNewsLetterTask).FullName,
                                              typeof(SendNewsLetterTask).Assembly.GetName().Name);

            return(job);
        }
 public MaterialConcept.MaterialType?GetMaterialType(ScheduledJob job)
 {
     if (job.Action is GetMaterialAction)
     {
         GetMaterialAction action = job.Action as GetMaterialAction;
         return(action.GetMaterial().GetMaterialType());
     }
     return(null);
 }
        protected override async Task Execute(ScheduledJob job, List <CompanyQuotesModel> companies)
        {
            var indicatorResults = await CalculateGlobalIndicators(companies, _indicators, job.JobId);

            foreach (var indicatorResult in indicatorResults)
            {
                await _indicatorService.StoreIntermediateResultsAsync(job.JobId, indicatorResult.Key, indicatorResult.Value);
            }
        }
        public void Execute_Should_Throw_When_ItemIsNull()
        {
            var mediator = Substitute.For <IMediator>();

            var scheduledJob = new ScheduledJob(_logger, mediator);

            scheduledJob.Item = null;

            scheduledJob.Execute();
        }
示例#23
0
        public ActionResult Details(int id)
        {
            ScheduledJob tenantScheduledJob = _db.ScheduledJobs.Find(id);

            if (tenantScheduledJob == null)
            {
                return(HttpNotFound());
            }
            return(View(tenantScheduledJob));
        }
示例#24
0
 internal static ScheduledJob CreateScheduledJob(dynamic job, int priority, DateTime? runAt)
 {
     var scheduled = new ScheduledJob
     {
         Priority = priority,
         Handler = HandlerSerializer.Serialize(job),
         RunAt = runAt
     };
     return scheduled;
 }
示例#25
0
        public static void InsertJob(IDbConnection db, DatabaseDialect dialect, ScheduledJob job)
        {
            var sql = "INSERT INTO ScheduledJob " +
                      "(Priority, Attempts, Handler, RunAt) " +
                      "VALUES (@Priority, @Attempts, @Handler, @RunAt); ";

            sql = AddInsertIdentity(dialect, sql);
            job.Id = db.Execute(sql, job);
            job.CreatedAt = db.Query<DateTime>("SELECT CreatedAt FROM ScheduledJob WHERE Id = @Id", new {job.Id}).Single();
        }
示例#26
0
        public static void UpdateJob(IDbConnection db, ScheduledJob job)
        {
            const string sql = "UPDATE ScheduledJob SET " +
                               "Priority = @Priority, Attempts = @Attempts, LastError = @LastError, RunAt = @RunAt, " +
                               "FailedAt = @FailedAt, SucceededAt = @SucceededAt, LockedAt = @LockedAt, " +
                               "LockedBy = @LockedBy, UpdatedAt = @UpdatedAt " +
                               "WHERE Id = @Id";

            db.Execute(sql, job);
        }
示例#27
0
        public void Periods_with_defined_endings_have_finite_occurrences()
        {
            var job = new ScheduledJob();
            var info = new Every(job).Hour().For(6).Days();
            Assert.AreEqual(24 * 6, info.AllOccurrences.Count());

            Assert.IsNotNull(info.NextOccurrence);
            Assert.IsNotNull(info.LastOccurrence);
            Assert.AreEqual(info.NextOccurrence, info.AllOccurrences.First());
            Assert.AreEqual(info.LastOccurrence, info.AllOccurrences.Last());
        }
示例#28
0
        public void Periods_with_undefined_endings_have_infinite_occurrences()
        {
            var job = new ScheduledJob();
            var info = new Every(job).Hour();
            Assert.Throws<ArgumentException>(() => { info.AllOccurrences.ToList(); });
            Assert.IsNull(info.LastOccurrence);

            var next = info.NextOccurrence;
            Assert.IsNotNull(next);
            Console.WriteLine(next);
        }
        // Token: 0x060005A5 RID: 1445 RVA: 0x000220B4 File Offset: 0x000202B4
        private Guid SubmitScheduledJobToScheduler(ScheduledJob job)
        {
            Guid result;

            using (IJobSchedulerHelper jobSchedulerHelper = this.jobSchedulerHelperFactory())
            {
                OneTimeJobManager.Logger.Debug("Adding new job to Job Engine");
                result = jobSchedulerHelper.AddJob(job);
            }
            return(result);
        }
示例#30
0
        public void Periods_with_defined_endings_have_finite_occurrences()
        {
            var job  = new ScheduledJob();
            var info = new Every(job).Hour().For(6).Days();

            Assert.AreEqual(24 * 6, info.AllOccurrences.Count());

            Assert.IsNotNull(info.NextOccurrence);
            Assert.IsNotNull(info.LastOccurrence);
            Assert.AreEqual(info.NextOccurrence, info.AllOccurrences.First());
            Assert.AreEqual(info.LastOccurrence, info.AllOccurrences.Last());
        }
示例#31
0
        public void Start_wrapped_thread()
        {
            // Arrange
            var threadWrapper = new Mock <IThreadWrapper>();
            var scheduledJob  = new ScheduledJob(new TimeSpan(), token => { }, token => { }, threadWrapper.Object);

            // Act
            scheduledJob.Start(_cancellatonTokenSource.Token);

            // Assert
            threadWrapper.Verify(x => x.Start(_cancellatonTokenSource.Token), Times.Once);
        }
示例#32
0
 /// <summary> 
 ///
 /// </summary>
 protected override void ProcessRecord()
 {
     //WriteObject(ForensicTimeline.GetInstances(Prefetch.GetInstances(volume)), true);
     WriteObject(ForensicTimeline.GetInstances(ScheduledJob.GetInstances(volume)), true);
     WriteObject(ForensicTimeline.GetInstances(FileRecord.GetInstances(volume)), true);
     WriteObject(ForensicTimeline.GetInstances(UsnJrnl.GetInstances(volume)), true);
     WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\DRIVERS")), true);
     WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SAM")), true);
     WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SECURITY")), true);
     WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SOFTWARE")), true);
     WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SYSTEM")), true);
 }
示例#33
0
        public async Task DisposesWrappedJob()
        {
            var job          = new DisposableJob();
            var scheduledJob = new ScheduledJob <DisposableJob>(() => job, new FakeSchedule(2), NullLoggerFactory.Instance, Clock.DefaultClock);

            using (var cts = new CancellationTokenSource())
            {
                await JobHost.RunAsync(scheduledJob, TimeSpan.FromSeconds(3), cts.Token);
            }

            Assert.True(job.DisposedCalls > 0);
        }
    private void sendCancelMessage(ScheduledJob job)
    {
        AgentMessage message = new AgentMessage(AgentMessage.PerformativeType.CANCEL);

        message.Sender         = coordinatorAgent.AId;
        message.Receiver       = job.AgentId;
        message.Protocol       = Protocols.FIPA_REQUEST;
        message.Content        = job.Action;
        message.ConversationId = job.ConversationId;
        coordinatorAgent.Send(message);
        job.JobStatus = ScheduledJob.Status.Cancelled;
    }
示例#35
0
        /// <summary>
        /// The ProcessRecord method calls TimeZone.CurrentTimeZone to return a TimeZone object.
        /// </summary>
        protected override void ProcessRecord()
        {
            switch (ParameterSetName)
            {
            case "ByVolume":
                WriteObject(ScheduledJob.GetInstances(volume), true);
                break;

            case "ByPath":
                WriteObject(ScheduledJob.Get(path));
                break;
            }
        }
        public ScheduledJob Create(JobDescriptionViewModel job)
        {
            var result = new ScheduledJob
            {
                IntervalType = ScheduledIntervalType.Days,
                IsEnabled = false,
                Name = job.Name,
                MethodName = "Execute",
                TypeName = job.TypeName,
                AssemblyName = job.AssemblyName,
                IsStaticMethod = true
            };

            if (result.NextExecution == DateTime.MinValue)
            {
                result.NextExecution = DateTime.Today;
            }

            _actualRepository.Save(result);

            return result;
        }
        public void Save(ScheduledJob job, RepeatInfo info = null)
        {
            var db = _connectionBuilder();
            if(job.Id == 0)
            {
                Queries.InsertJob(db, _dialect, job);
            }
            else
            {
                job.UpdatedAt = DateTime.Now;
                Queries.UpdateJob(db, job);
            }

            var existing = Queries.GetRepeatInfo(db, job);
            if(existing == null)
            {
                Queries.InsertRepeatInfo(db, _dialect, job, info);
            }
            else
            {
                Queries.UpdateRepeatInfo(db, _dialect, job, info);
            }
        }
示例#38
0
 internal JobPart(SchedulingService service, ScheduledJob queueEntry)
 {
     _service = service;
     _queueEntry = queueEntry;
 }
示例#39
0
		public override Job2 NewJob(string definitionName, string definitionPath)
		{
			if (!string.IsNullOrEmpty(definitionName))
			{
				Job2 scheduledJob = null;
				try
				{
					ScheduledJobDefinition scheduledJobDefinition = ScheduledJobDefinition.LoadFromStore(definitionName, definitionPath);
					scheduledJob = new ScheduledJob(scheduledJobDefinition.Command, scheduledJobDefinition.Name, scheduledJobDefinition);
				}
				catch (FileNotFoundException fileNotFoundException)
				{
				}
				return scheduledJob;
			}
			else
			{
				throw new PSArgumentException("definitionName");
			}
		}
 public static ScheduledJob CreateScheduledJob(string parameters, long entityKindId, long parentId, long ID, global::System.Guid tid, string name, long createdById, long modifiedById, global::System.DateTimeOffset created, global::System.DateTimeOffset modified, long maximumRuntimeMinutes, long autoDeleteIfNotScheduledDays, long maxRestartAttempts, long maxRestartWaitTimeMinutes, long historyDepth)
 {
     ScheduledJob scheduledJob = new ScheduledJob();
     scheduledJob.Parameters = parameters;
     scheduledJob.EntityKindId = entityKindId;
     scheduledJob.ParentId = parentId;
     scheduledJob.Id = ID;
     scheduledJob.Tid = tid;
     scheduledJob.Name = name;
     scheduledJob.CreatedById = createdById;
     scheduledJob.ModifiedById = modifiedById;
     scheduledJob.Created = created;
     scheduledJob.Modified = modified;
     scheduledJob.MaximumRuntimeMinutes = maximumRuntimeMinutes;
     scheduledJob.AutoDeleteIfNotScheduledDays = autoDeleteIfNotScheduledDays;
     scheduledJob.MaxRestartAttempts = maxRestartAttempts;
     scheduledJob.MaxRestartWaitTimeMinutes = maxRestartWaitTimeMinutes;
     scheduledJob.HistoryDepth = historyDepth;
     return scheduledJob;
 }
示例#41
0
		public ScheduledJob StartJob()
		{
			this.IsDisposed();
			ScheduledJob scheduledJob = new ScheduledJob(this._invocationInfo.Command, this._invocationInfo.Name, this);
			scheduledJob.StartJob();
			return scheduledJob;
		}
示例#42
0
 public Every(ScheduledJob job) : this(job, 1)
 {
     _job = job;
 }
示例#43
0
        private void TimerCallbackHandler(object data)
        {
            var waitTime = _head.NextOccurence - DateTime.Now;
            var waitMilliseconds = (long) waitTime.TotalMilliseconds;

            if (waitMilliseconds > 0)
            {
                _timer.Change(waitMilliseconds, Timeout.Infinite);
                return;
            }

            ThreadPool.QueueUserWorkItem(WaitCallbackHandler, _head);
            _head.Advance();
            _queue.Add(_head);
            _head = _queue.DeleteMin();
            TimerCallbackHandler(null);
        }
 public void Delete(ScheduledJob job)
 {
     var db = _connectionBuilder();
     Queries.DeleteJob(db, job);
 }
示例#45
0
		private static void SaveStatusToFile(ScheduledJob job, FileStream fs)
		{
			StatusInfo statusInfo = new StatusInfo(job.InstanceId, job.Name, job.Location, job.Command, job.StatusMessage, job.JobStateInfo.State, job.HasMoreData, job.PSBeginTime, job.PSEndTime, job.Definition);
			XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
			netDataContractSerializer.WriteObject(fs, statusInfo);
			fs.Flush();
		}
示例#46
0
        /// <summary>
        /// Serializes a ScheduledJob and saves it to store.
        /// </summary>
        /// <param name="job">ScheduledJob</param>
        internal static void SaveJobToStore(ScheduledJob job)
        {
            string outputPath = job.Definition.OutputPath;
            if (string.IsNullOrEmpty(outputPath))
            {
                string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSaveJobNoFilePathSpecified,
                    job.Name);
                throw new ScheduledJobException(msg);
            }

            FileStream fsStatus = null;
            FileStream fsResults = null;
            try
            {
                // Check the job store results and if maximum number of results exist
                // remove the oldest results folder to make room for these new results.
                CheckJobStoreResults(outputPath, job.Definition.ExecutionHistoryLength);

                fsStatus = ScheduledJobStore.CreateFileForJobRunItem(
                    outputPath,
                    job.PSBeginTime ?? DateTime.MinValue,
                    ScheduledJobStore.JobRunItem.Status);

                // Save status only in status file stream.
                SaveStatusToFile(job, fsStatus);

                fsResults = ScheduledJobStore.CreateFileForJobRunItem(
                    outputPath,
                    job.PSBeginTime ?? DateTime.MinValue,
                    ScheduledJobStore.JobRunItem.Results);

                // Save entire job in results file stream.
                SaveResultsToFile(job, fsResults);
            }
            finally
            {
                if (fsStatus != null)
                {
                    fsStatus.Close();
                }

                if (fsResults != null)
                {
                    fsResults.Close();
                }
            }
        }
示例#47
0
 public static RepeatInfo GetRepeatInfo(IDbConnection db, ScheduledJob job)
 {
     var result = db.Query("SELECT * FROM RepeatInfo WHERE ScheduledJobId = @Id", job).SingleOrDefault();
     if (result == null) return null;
     var repeatInfo = new RepeatInfo(result.Start, new DatePeriod(result.PeriodFrequency, result.PeriodQuantifier));
     return repeatInfo;
 }
示例#48
0
 /// <summary>
 /// Adds a scheduled job for automatic execution by this service.
 /// </summary>
 /// <param name="schedule">A method for computation of occurrences in the schedule, taking last execution as parameter.</param>
 /// <param name="executionWrapper">The execution wrapper method to be invoked on each occurence of the job.</param>
 /// <returns>The newly scheduled job.</returns>
 public ScheduledJob AddScheduledJob(Func<DateTime, DateTime> schedule, JobExecutionWrapper executionWrapper)
 {
     var entry = new ScheduledJob(schedule, executionWrapper, DateTime.Now);
     _queue.Add(entry);
     return entry;
 }
示例#49
0
        /// <summary>
        /// Starts the scheduled job immediately.  A ScheduledJob object is 
        /// returned that represents the running command, and this returned
        /// job is also added to the local job repository.  Job results are
        /// not written to the job store.
        /// </summary>
        /// <returns>ScheduledJob object for running job</returns>
        public ScheduledJob StartJob()
        {
            IsDisposed();

            ScheduledJob job = new ScheduledJob(_invocationInfo.Command, _invocationInfo.Name, this);
            job.StartJob();

            return job;
        }
 public virtual void Save(ScheduledJob scheduledJob)
 {
     scheduledJob.Save();
 }
示例#51
0
		internal static void SaveJobToStore(ScheduledJob job)
		{
			DateTime valueOrDefault;
			DateTime minValue;
			string outputPath = job.Definition.OutputPath;
			if (!string.IsNullOrEmpty(outputPath))
			{
				FileStream fileStream = null;
				FileStream fileStream1 = null;
				try
				{
					ScheduledJobSourceAdapter.CheckJobStoreResults(outputPath, job.Definition.ExecutionHistoryLength);
					string str = outputPath;
					DateTime? pSBeginTime = job.PSBeginTime;
					if (pSBeginTime.HasValue)
					{
						valueOrDefault = pSBeginTime.GetValueOrDefault();
					}
					else
					{
						valueOrDefault = DateTime.MinValue;
					}
					fileStream = ScheduledJobStore.CreateFileForJobRunItem(str, valueOrDefault, ScheduledJobStore.JobRunItem.Status);
					ScheduledJobSourceAdapter.SaveStatusToFile(job, fileStream);
					string str1 = outputPath;
					DateTime? nullable = job.PSBeginTime;
					if (nullable.HasValue)
					{
						minValue = nullable.GetValueOrDefault();
					}
					else
					{
						minValue = DateTime.MinValue;
					}
					fileStream1 = ScheduledJobStore.CreateFileForJobRunItem(str1, minValue, ScheduledJobStore.JobRunItem.Results);
					ScheduledJobSourceAdapter.SaveResultsToFile(job, fileStream1);
				}
				finally
				{
					if (fileStream != null)
					{
						fileStream.Close();
					}
					if (fileStream1 != null)
					{
						fileStream1.Close();
					}
				}
				return;
			}
			else
			{
				string str2 = StringUtil.Format(ScheduledJobErrorStrings.CantSaveJobNoFilePathSpecified, job.Name);
				throw new ScheduledJobException(str2);
			}
		}
示例#52
0
        public static void UpdateRepeatInfo(IDbConnection db, DatabaseDialect dialect, ScheduledJob job, RepeatInfo info)
        {
            const string sql = "UPDATE RepeatInfo SET " +
                               "PeriodFrequency = @PeriodFrequency, " +
                               "PeriodQuantifier = @PeriodQuantifier, " +
                               "Start = @Start, " +
                               "IncludeWeekends = @IncludeWeekends " +
                               "WHERE ScheduledJobId = @ScheduledJobId;";

            db.Execute(sql, new
            {
                ScheduledJobId = job.Id,
                info.PeriodFrequency,
                info.PeriodQuantifier,
                info.Start,
                info.IncludeWeekends
            });
        }
示例#53
0
		private static void SaveResultsToFile(ScheduledJob job, FileStream fs)
		{
			XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
			netDataContractSerializer.WriteObject(fs, job);
			fs.Flush();
		}
示例#54
0
 public static void DeleteJob(IDbConnection db, ScheduledJob job)
 {
     const string sql = "DELETE FROM ScheduledJob WHERE Id = @Id; DELETE FROM RepeatInfo WHERE ScheduledJobId = @Id;";
     db.Execute(sql, job);
 }
示例#55
0
 public Every(ScheduledJob job, int n)
 {
     _job = job;
     _n = n;
 }
示例#56
0
 /// <summary>
 /// Writes the job (which implements ISerializable) to the provided
 /// file stream.
 /// </summary>
 /// <param name="job">ScheduledJob job to save</param>
 /// <param name="fs">FileStream</param>
 private static void SaveResultsToFile(ScheduledJob job, FileStream fs)
 {
     XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();
     serializer.WriteObject(fs, job);
     fs.Flush();
 }
示例#57
0
        public static void InsertRepeatInfo(IDbConnection db, DatabaseDialect dialect, ScheduledJob job, RepeatInfo info)
        {
            const string sql = "INSERT INTO RepeatInfo " +
                               "(ScheduledJobId, PeriodFrequency, PeriodQuantifier, Start, IncludeWeekends) " +
                               "VALUES (@ScheduledJobId, @PeriodFrequency, @PeriodQuantifier, @Start, @IncludeWeekends);";

            db.Execute(sql, new
            {
                ScheduledJobId = job.Id,
                info.PeriodFrequency,
                info.PeriodQuantifier,
                info.Start,
                info.IncludeWeekends
            });
        }
示例#58
0
 public void Start()
 {
     _head = _queue.DeleteMin();
     TimerCallbackHandler(null);
 }
示例#59
0
 public static void AddToBatch(IDbConnection db, DatabaseDialect dialect, Batch batch, ScheduledJob job)
 {
     const string sql = "INSERT INTO BatchJob (BatchId, ScheduledJobId) VALUES (@BatchId, @ScheduledJobId)";
     db.Execute(sql, new { BatchId = batch.Id, ScheduledJobId = job.Id });
 }
示例#60
0
        /// <summary>
        /// Creates a new Job2 object based on a definition name
        /// that can be run manually.  If the path parameter is 
        /// null then a default location will be used to find the 
        /// job definition by name.
        /// </summary>
        /// <param name="definitionName">ScheduledJob definition name</param>
        /// <param name="definitionPath">ScheduledJob definition file path</param>
        /// <returns>Job2 object</returns>
        public override Job2 NewJob(string definitionName, string definitionPath)
        {
            if (string.IsNullOrEmpty(definitionName))
            {
                throw new PSArgumentException("definitionName");
            }

            Job2 rtnJob = null;
            try
            {
                ScheduledJobDefinition scheduledJobDef =
                    ScheduledJobDefinition.LoadFromStore(definitionName, definitionPath);

                rtnJob = new ScheduledJob(
                    scheduledJobDef.Command,
                    scheduledJobDef.Name,
                    scheduledJobDef);
            }
            catch (FileNotFoundException)
            { 
                // Return null if no job definition exists.
            }

            return rtnJob;
        }