Пример #1
0
        private async Task <ITaskState> DoTask(ITaskState taskState, ScheduleMode mode, CancellationToken cancellationToken)
        {
            var configuredOn = DateTimeOffset.Now;

            using (db = dbf.GetWebDbContext <ServiceDb>())
            {
                await db.Database.EnsureCreatedAsync();

                //var sm = new ServerManager();
                //foreach (var site in sm.Sites)
                //{
                //    await AddSiteFolder(configuredOn, site);
                //}
                foreach (var fs in options.FolderSources)
                {
                    await AddFolderSource(configuredOn, fs);
                }
                var staleList = await db.SourceFolders
                                .Include(x => x.Backups)
                                .Where(x => x.ConfiguredOn < configuredOn).ToArrayAsync();

                foreach (var sf in staleList)
                {
                    var backups = sf.Backups.ToArray();
                    db.Backups.RemoveRange(backups);
                    db.SourceFolders.Remove(sf);
                    log.LogInformation($"{sf.DisplayName} {sf.FullPath} (with {backups.Count()} backups) removed");
                }
                await db.SaveChangesAsync();

                var count = db.SourceFolders.Count();
                log.LogInformation($"found {count} source folders in database");
                return(null);// Task.FromResult<ITaskState>(null);
            }
        }
Пример #2
0
            public unsafe JobScheduleParameters(void *jobData, IntPtr reflectionData, JobHandle jobDependency,
                                                ScheduleMode scheduleMode, int jobDataSize = 0, int schedule = 3)
            {
                // Default is 0; code-gen should set to a correct size.
                if (jobDataSize == 0)
                {
                    throw new InvalidOperationException("JobScheduleParameters (size) should be set by code gen.");
                }
                // Default is 1; however, the function created by code gen will always return 2.
                if (schedule != 2)
                {
                    throw new InvalidOperationException(
                              "JobScheduleParamaters (rc of ScheduleJob_Gen) should be set by code gen.");
                }

                Assert.IsTrue(sizeof(JobMetaData) % 16 == 0);
                int headerSize = sizeof(JobMetaData);
                int size       = headerSize + jobDataSize;

                void *mem = UnsafeUtility.Malloc(size, 16, Allocator.TempJob);

                UnsafeUtility.MemClear(mem, size);
                UnsafeUtility.MemCpy(((byte *)mem + headerSize), jobData, jobDataSize);
                UnsafeUtility.AssertHeap(mem);

                Dependency     = jobDependency;
                JobDataPtr     = (IntPtr)mem;
                ReflectionData = reflectionData;
                ScheduleMode   = (int)scheduleMode;
            }
Пример #3
0
        private async Task <ITaskState> DoTask(ITaskState taskState, ScheduleMode mode, CancellationToken cancellationToken)
        {
            var currentTime = DateTime.Now;

            if (options.PollingSchedules != null)
            {
                foreach (var item in options.PollingSchedules)
                {
                    var pw = EnsureWrapped(item);
                    if (IsDue(currentTime, pw))
                    {
                        pw.LastRunTime = pw.NextRunTime;
                        pw.NextRunTime = pw.Schedule.GetNextOccurrence(pw.NextRunTime);
                        var r = await Poll(item);

                        if (r)
                        {
                            log.LogInformation($"Poll {item.Url} succeeded");
                        }
                    }
                }
            }
            else
            {
                log.LogInformation("no urls provided");
            }
            return(null);
        }
Пример #4
0
        /// <summary> Schedule a <see cref="IJobEventReader{T}"/> job. </summary>
        /// <param name="jobData"> The job. </param>
        /// <param name="eventSystem"> The event system. </param>
        /// <param name="dependsOn"> The job handle dependency. </param>
        /// <typeparam name="TJob"> The type of the job. </typeparam>
        /// <typeparam name="T"> The type of the key in the hash map. </typeparam>
        /// <returns> The handle to job. </returns>
        public static unsafe JobHandle Schedule <TJob, T>(
            this TJob jobData, EventSystemBase eventSystem, JobHandle dependsOn = default)
            where TJob : struct, IJobEventReader <T>
            where T : struct
        {
            dependsOn = eventSystem.GetEventReaders <T>(dependsOn, out var events);

            for (var i = 0; i < events.Count; i++)
            {
                var fullData = new EventJobReaderStruct <TJob, T>
                {
                    Reader  = events[i],
                    JobData = jobData,
                    Index   = i,
                };

#if UNITY_2020_2_OR_NEWER
                const ScheduleMode scheduleMode = ScheduleMode.Parallel;
#else
                const ScheduleMode scheduleMode = ScheduleMode.Batched;
#endif

                var scheduleParams = new JobsUtility.JobScheduleParameters(
                    UnsafeUtility.AddressOf(ref fullData),
                    EventJobReaderStruct <TJob, T> .Initialize(),
                    dependsOn,
                    scheduleMode);

                dependsOn = JobsUtility.Schedule(ref scheduleParams);
            }

            eventSystem.AddJobHandleForConsumer <T>(dependsOn);

            return(dependsOn);
        }
Пример #5
0
        /// <summary>
        /// Starts this <see cref="MicroThread"/> with the specified function.
        /// </summary>
        /// <param name="microThreadFunction">The micro thread function.</param>
        /// <param name="flags">The flags.</param>
        /// <param name="scheduleMode">The schedule mode.</param>
        /// <exception cref="System.InvalidOperationException">MicroThread was already started before.</exception>
        public void Start(Func <Task> microThreadFunction, ScheduleMode scheduleMode = ScheduleMode.Last)
        {
            ScriptId = microThreadFunction.Target.GetType().Name;

            // TODO: Interlocked compare exchange?
            if (Interlocked.CompareExchange(ref state, (int)MicroThreadState.Starting, (int)MicroThreadState.None) != (int)MicroThreadState.None)
            {
                throw new InvalidOperationException("MicroThread was already started before.");
            }

            Action wrappedMicroThreadFunction = async() =>
            {
                try
                {
                    State = MicroThreadState.Running;

                    await microThreadFunction();

                    if (State != MicroThreadState.Running)
                    {
                        throw new InvalidOperationException("MicroThread completed in an invalid state.");
                    }
                    State = MicroThreadState.Completed;
                }
                catch (OperationCanceledException e)
                {
                    // Exit gracefully on cancellation exceptions
                    SetException(e);
                }
                catch (Exception e)
                {
                    Scheduler.Log.Error("Unexpected exception while executing a micro-thread. Reason: {0}", new object[] { e });
                    SetException(e);
                }
                finally
                {
                    lock (Scheduler.allMicroThreads)
                    {
                        Scheduler.allMicroThreads.Remove(AllLinkedListNode);
                    }
                }
            };

            Action callback = () =>
            {
                SynchronizationContext = new MicroThreadSynchronizationContext(this);
                SynchronizationContext.SetSynchronizationContext(SynchronizationContext);

                wrappedMicroThreadFunction();
            };

            lock (Scheduler.allMicroThreads)
            {
                Scheduler.allMicroThreads.AddLast(AllLinkedListNode);
            }

            ScheduleContinuation(scheduleMode, callback);
        }
 public static void SendNotification
     (string id
     , DateTime when
     , NotificationData data
     , bool cancelPrevious       = false
     , ScheduleMode scheduleMode = ScheduleMode.None)
 {
     SendNotification(id, when, TimeSpan.Zero, data, cancelPrevious, scheduleMode);
 }
Пример #7
0
        public static void TryScheduleNextEvent(ScheduleMode mode = ScheduleMode.Normal)
        {
            if (ListAllyAvailable.Count == 0)
            {
                if (mode != ScheduleMode.Init)
                {
                    Util.Msg("No available Reunion pawns, Reunion events will not fire from now on.");
                }
                return;
            }

            if (mode != ScheduleMode.Forced &&             // don't check if forced
                NextEventTick == -1)
            {
                // another event is currently happening
                if (Prefs.DevMode)
                {
                    if (mode != ScheduleMode.Init)
                    {
                        Util.Msg("Tried to schedule an event but is in the middle of an event.");
                    }
                }

                return;
            }

            if (mode != ScheduleMode.Forced &&             // don't check if forced
                mode != ScheduleMode.SettingsUpdated &&    // only updating settings will force a reschedule
                NextEventTick > Find.TickManager.TicksGame)
            {
                // another event is already scheduled
                if (Prefs.DevMode)
                {
                    if (mode != ScheduleMode.Init)
                    {
                        Util.Msg("Tried to schedule an event but another event has already been scheduled.");
                    }
                }
                return;
            }

            var min = Settings.minDaysBetweenEvents * GenDate.TicksPerDay;

            if (min == 0)
            {
                min = 1;                       // limit it to at least 1 tick
            }
            var max = Settings.maxDaysBetweenEvents * GenDate.TicksPerDay;

            NextEventTick = Find.TickManager.TicksGame + Random.Range(min, max);

#if TESTING
            NextEventTick = Find.TickManager.TicksGame + 1000;
#endif
            Util.PrintNextEventTimeRemaining();
        }
        public void IJobEntityBatch_WithNoBatching_HasCorrectIndices(
            [Values(ScheduleMode.Parallel, ScheduleMode.Single, ScheduleMode.Run, ScheduleMode.RunWithoutJobs)] ScheduleMode scheduleMode)
        {
            var archetypeA = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp));

            using (var query = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestSharedComp)))
                using (var entities = m_Manager.CreateEntity(archetypeA, 100, Allocator.TempJob))
                {
                    var val = 0;
                    foreach (var entity in entities)
                    {
                        m_Manager.SetComponentData(entity, new EcsTestData()
                        {
                            value = val
                        });
                        m_Manager.SetSharedComponentData(entity, new EcsTestSharedComp()
                        {
                            value = val
                        });
                        val++;
                    }

                    var job = new CheckBatchIndices {
                        EcsTestDataTypeHandle = EmptySystem.GetComponentTypeHandle <EcsTestData>()
                    };
                    var jobWithIndex = new CheckBatchAndFirstEntityIndices {
                        EcsTestDataTypeHandle = EmptySystem.GetComponentTypeHandle <EcsTestData>()
                    };

                    switch (scheduleMode)
                    {
                    case ScheduleMode.Parallel:
                        job.ScheduleParallel(query).Complete();
                        jobWithIndex.ScheduleParallel(query).Complete();
                        break;

                    case ScheduleMode.Single:
                        job.Schedule(query).Complete();
                        jobWithIndex.Schedule(query).Complete();
                        break;

                    case ScheduleMode.Run:
                        job.Run(query);
                        jobWithIndex.Run(query);
                        break;

                    case ScheduleMode.RunWithoutJobs:
                        JobEntityBatchExtensions.RunWithoutJobs(ref job, query);
                        JobEntityBatchIndexExtensions.RunWithoutJobs(ref jobWithIndex, query);
                        break;
                    }
                }
        }
        internal static unsafe JobHandle ScheduleInternal <T>(
            ref T jobData,
            EntityQuery query,
            JobHandle dependsOn,
            ScheduleMode mode,
            int batchesPerChunk,
            bool isParallel = true)
            where T : struct, IJobEntityBatch
        {
            var queryImpl = query._GetImpl();
            var queryData = queryImpl->_QueryData;

            var cachedChunks = queryData->GetMatchingChunkCache();

            // Don't schedule the job if there are no chunks to work on
            var chunkCount = cachedChunks.Length;

            JobEntityBatchWrapper <T> jobEntityBatchWrapper = new JobEntityBatchWrapper <T>
            {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                // All IJobEntityBatch jobs have a EntityManager safety handle to ensure that BeforeStructuralChange throws an error if
                // jobs without any other safety handles are still running (haven't been synced).
                safety = new EntitySafetyHandle {
                    m_Safety = queryImpl->SafetyHandles->GetEntityManagerSafetyHandle()
                },
#endif

                MatchingArchetypes = queryData->MatchingArchetypes,
                CachedChunks       = cachedChunks,
                Filter             = queryImpl->_Filter,

                JobData      = jobData,
                JobsPerChunk = batchesPerChunk,
                IsParallel   = isParallel ? 1 : 0
            };

            var scheduleParams = new JobsUtility.JobScheduleParameters(
                UnsafeUtility.AddressOf(ref jobEntityBatchWrapper),
                isParallel
                ? JobEntityBatchProducer <T> .InitializeParallel()
                : JobEntityBatchProducer <T> .InitializeSingle(),
                dependsOn,
                mode);

            if (!isParallel)
            {
                return(JobsUtility.Schedule(ref scheduleParams));
            }
            else
            {
                return(JobsUtility.ScheduleParallelFor(ref scheduleParams, chunkCount * batchesPerChunk, 1));
            }
        }
Пример #10
0
        internal void Reschedule(ScheduleMode scheduleMode)
        {
            lock (Scheduler.scheduledMicroThreads)
            {
                if (ScheduledLinkedListNode.Index != -1)
                {
                    Scheduler.scheduledMicroThreads.Remove(ScheduledLinkedListNode);

                    Schedule(scheduleMode);
                }
            }
        }
Пример #11
0
 private Schedule(ScheduleInterval[] intervals, ScheduleMode mode, bool normalize, string scheduleName)
 {
     if (intervals == null)
     {
         this.intervals = new ScheduleInterval[0];
     }
     else
     {
         this.intervals = (normalize ? Schedule.NormalizeIntervals(intervals) : intervals);
     }
     this.mode         = mode;
     this.scheduleName = scheduleName;
 }
Пример #12
0
        internal void Schedule(PriorityQueueNode <SchedulerEntry> schedulerEntry, ScheduleMode scheduleMode)
        {
            var nextCounter = SchedulerCounter++;

            if (scheduleMode == ScheduleMode.First)
            {
                nextCounter = -nextCounter;
            }

            schedulerEntry.Value.SchedulerCounter = nextCounter;

            scheduledEntries.Enqueue(schedulerEntry);
        }
Пример #13
0
        private void Schedule(ScheduleMode scheduleMode)
        {
            var nextCounter = Scheduler.SchedulerCounter++;

            if (scheduleMode == ScheduleMode.First)
            {
                nextCounter = -nextCounter;
            }

            schedulerCounter = nextCounter;

            Scheduler.scheduledMicroThreads.Enqueue(ScheduledLinkedListNode);
        }
Пример #14
0
        /// <summary>
        /// 打开TDRS服务
        /// </summary>
        private void OpenTDRS()
        {
            //ScheduleMode m_ScheduleMode = new ScheduleMode();
            if (m_ScheduleMode == null)
            {
                m_ScheduleMode = new ScheduleMode();
            }
            m_ScheduleMode.OnMessageStatusChanges += new ScheduleMode.MessageStatusChanges(SetMessageInfo);
            m_ScheduleMode.OnMsCountChanges       += new ScheduleMode.MsCountChanges(PrintCountToUI);
            m_ScheduleMode.Start(m_vmMSConfig);

            //需要在开启模块之后开启
            LoadSetParaTime();
        }
Пример #15
0
 public ScheduledEvent(int heatingZoneId,
                       TimeSpan time,
                       double temperature,
                       DateTime?validFrom,
                       DateTime?validTo,
                       ScheduleMode mode)
 {
     HeatingZoneId = heatingZoneId;
     Time          = time;
     Temperature   = temperature;
     ValidFrom     = validFrom;
     ValidTo       = validTo;
     Mode          = mode;
 }
Пример #16
0
        // 设为internal来阻止外部派生。
        internal PlaybillItem(PlaySource playSource, ScheduleMode scheduleMode)
        {
            if (playSource == null)
            {
                throw new ArgumentNullException("playSource");
            }

            if (!Enum.IsDefined(typeof(ScheduleMode), scheduleMode))
            {
                throw new System.ComponentModel.InvalidEnumArgumentException("scheduleMode", (int)scheduleMode, typeof(ScheduleMode));
            }
            this.PlaySource   = playSource;
            this.ScheduleMode = scheduleMode;
        }
Пример #17
0
        internal void ScheduleContinuation(ScheduleMode scheduleMode, Action callback)
        {
            Debug.Assert(callback != null);
            lock (Scheduler.scheduledMicroThreads)
            {
                var node = NewCallback();
                node.MicroThreadAction = callback;

                if (ScheduledLinkedListNode.Index == -1)
                {
                    Schedule(scheduleMode);
                }
            }
        }
Пример #18
0
        internal void ScheduleContinuation(ScheduleMode scheduleMode, SendOrPostCallback callback, object callbackState)
        {
            Debug.Assert(callback != null);
            lock (Scheduler.scheduledMicroThreads)
            {
                var node = NewCallback();
                node.SendOrPostCallback = callback;
                node.CallbackState      = callbackState;

                if (ScheduledLinkedListNode.Index == -1)
                {
                    Schedule(scheduleMode);
                }
            }
        }
Пример #19
0
        public static Schedule FromByteArray(byte[] bitmaps)
        {
            ScheduleInterval[] intervalsFromWeekBitmap = ScheduleInterval.GetIntervalsFromWeekBitmap(bitmaps);
            ScheduleMode       scheduleMode            = Schedule.CalculateMode(intervalsFromWeekBitmap);

            if (scheduleMode == ScheduleMode.Never)
            {
                return(Schedule.Never);
            }
            if (scheduleMode == ScheduleMode.Always)
            {
                return(Schedule.Always);
            }
            return(new Schedule(intervalsFromWeekBitmap, scheduleMode));
        }
Пример #20
0
        internal static unsafe JobHandle ScheduleInternal_1 <T>(ref T jobData, ComponentSystemBase system,
                                                                int innerloopBatchCount,
                                                                JobHandle dependsOn, ScheduleMode mode)
            where T : struct
        {
            JobStruct_ProcessInfer_1 <T> fullData;

            fullData.Data = jobData;

            var isParallelFor = innerloopBatchCount != -1;

            IJobProcessComponentDataUtility.Initialize(system, typeof(T), typeof(JobStruct_Process1 <,>), isParallelFor,
                                                       ref JobStruct_ProcessInfer_1 <T> .Cache, out fullData.Iterator);
            return(Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.Iterator.m_Length, innerloopBatchCount,
                            isParallelFor, ref JobStruct_ProcessInfer_1 <T> .Cache, dependsOn, mode));
        }
Пример #21
0
        internal void ScheduleContinuation(ScheduleMode scheduleMode, Action callback)
        {
            Debug.Assert(callback != null);
            lock (Scheduler.scheduledMicroThreads)
            {
                callbackFromActionBuilder.MicroThreadAction = callback;
                Callback += callbackFromActionBuilder.MicroThreadCallback;

                if (ScheduledLinkedListNode.Index != -1)
                {
                    throw new InvalidOperationException("MicroThread was already scheduled, something is probably wrong.");
                }

                Schedule(scheduleMode);
            }
        }
Пример #22
0
 internal void Reschedule(ScheduleMode scheduleMode, long newPriority)
 {
     lock (Scheduler.ScheduledEntries)
     {
         if (ScheduledLinkedListNode.Index != -1)
         {
             Scheduler.ScheduledEntries.Remove(ScheduledLinkedListNode);
             ScheduledLinkedListNode.Value.Priority = newPriority;
             Scheduler.Schedule(ScheduledLinkedListNode, scheduleMode);
         }
         else
         {
             ScheduledLinkedListNode.Value.Priority = newPriority;
         }
     }
 }
        void RunTest(bool readOnly, ScheduleMode schedule)
        {
            var system = World.GetOrCreateSystem <PerfTestSystem>();
            var name   = (readOnly ? "ReadOnly" : "Write") + "_" + schedule.ToString();

            Measure.Method(() =>
            {
                system.ReadOnly = false;
                system.Schedule = schedule;
                system.Update();
            })
            .SampleGroup(name)
            .MeasurementCount(5)
            .IterationsPerMeasurement(1)
            .Run();
        }
Пример #24
0
        internal void ScheduleContinuation(ScheduleMode scheduleMode, SendOrPostCallback callback, object callbackState)
        {
            Debug.Assert(callback != null);
            lock (Scheduler.scheduledMicroThreads)
            {
                callbackSendPostCallbackBuilder.SendOrPostCallback = callback;
                callbackSendPostCallbackBuilder.CallbackState      = callbackState;
                Callback += callbackSendPostCallbackBuilder.MicroThreadCallback;

                if (ScheduledLinkedListNode.Index != -1)
                {
                    throw new InvalidOperationException("MicroThread was already scheduled, something is probably wrong.");
                }

                Schedule(scheduleMode);
            }
        }
Пример #25
0
        public ScheduleInfo(DateTime startTime, TimeSpan duration, ScheduleMode scheduleMode)
        {
            if (duration < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("duration",
                                                      string.Format("<{0}>无效,不能小于TimeSpan.Zero。", duration));
            }

            if (!Enum.IsDefined(typeof(ScheduleMode), scheduleMode))
            {
                throw new System.ComponentModel.InvalidEnumArgumentException("scheduleMode", (int)scheduleMode, typeof(ScheduleMode));
            }

            StartTime    = startTime;
            Duration     = duration;
            ScheduleMode = scheduleMode;
        }
 public EventDetailModel(int id,
                         int heatingZoneId,
                         string heatingZoneName,
                         DateTime time,
                         double temperature,
                         DateTime?validFrom,
                         DateTime?validTo,
                         ScheduleMode mode)
 {
     Id                   = id;
     HeatingZoneId        = heatingZoneId;
     HeatingZoneName      = heatingZoneName;
     Time                 = time;
     Temperature          = temperature;
     ValidFrom            = validFrom;
     ValidTo              = validTo;
     SelectedScheduleMode = mode;
 }
Пример #27
0
        private async Task ExecuteTask(ScheduledTaskWrapper taskWrapper, ScheduleMode mode, CancellationToken cancellationToken, params object[] args)
        {
            try
            {
                if (taskWrapper.Task is ScheduledTask)
                {
                    var task  = taskWrapper.Task as ScheduledTask;
                    var count = task.Pipeline.Count();
                    var msg   = $"Starting task {task.GetType().Name} [{mode.ToString()}]";
                    if (count > 1)
                    {
                        msg = $"{msg} (pipeline of {task.Pipeline.Count()} items)";
                        //log.LogInformation($"Starting task {task.GetType().Name} (pipeline of {task.Pipeline.Count()} items)");
                    }
                    log.Information(msg);
                }
                var sw = new Stopwatch();
                using (var sm = new SemaphoreSlim(1, 1))
                {
                    await sm.WaitAsync();

                    taskWrapper.IsRunning = true;
                    //taskWrapper.Task.SetMode()
                    sw.Start();
                    await taskWrapper.Task.ExecuteAsync(mode, cancellationToken, args);

                    sw.Stop();
                    taskWrapper.IsRunning = false;
                    log.Information($"Task {taskWrapper.Task.GetType().Name} completed in {sw.Elapsed}, will run next at {taskWrapper.NextRunTime.ToLocalTime().ToDefaultWithTime()}");
                }
            }
            catch (Exception ex)
            {
                var ex_args = new UnobservedTaskExceptionEventArgs(
                    ex as AggregateException ?? new AggregateException(ex));

                UnobservedTaskException?.Invoke(this, ex_args);

                if (!ex_args.Observed)
                {
                    throw;
                }
            }
        }
Пример #28
0
        private DateTime CalculateTriggerTime(TimeSpan at, ScheduleMode mode)
        {
            var sunData = sunDataService.GetLatest();

            DateTime calculatedAt = DateTime.Today;

            if (mode == ScheduleMode.Sunrise)
            {
                calculatedAt = calculatedAt.Add(sunData.Sunrise.TimeOfDay);
            }

            if (mode == ScheduleMode.Sunset)
            {
                calculatedAt = calculatedAt.Add(sunData.Sunset.TimeOfDay);
            }

            // set the event time, if together with sunrise/sunset add for example 5 minutes from that time
            return(calculatedAt.Add(at));
        }
Пример #29
0
        private static unsafe JobHandle ScheduleInternal <TJob, T>(
            this TJob jobData,
            EventSystemBase eventSystem,
            JobHandle dependsOn,
            bool isParallel)
            where TJob : struct, IJobEvent <T>
            where T : struct
        {
            dependsOn = eventSystem.GetEventReaders <T>(dependsOn, out var events);

            for (var i = 0; i < events.Count; i++)
            {
                var reader = events[i];

                var fullData = new JobEventProducer <TJob, T>
                {
                    Reader     = reader,
                    JobData    = jobData,
                    IsParallel = isParallel,
                };

#if UNITY_2020_2_OR_NEWER
                const ScheduleMode scheduleMode = ScheduleMode.Parallel;
#else
                const ScheduleMode scheduleMode = ScheduleMode.Batched;
#endif

                var scheduleParams = new JobsUtility.JobScheduleParameters(
                    UnsafeUtility.AddressOf(ref fullData),
                    isParallel ? JobEventProducer <TJob, T> .InitializeParallel() : JobEventProducer <TJob, T> .InitializeSingle(),
                    dependsOn,
                    scheduleMode);

                dependsOn = isParallel
                    ? JobsUtility.ScheduleParallelFor(ref scheduleParams, reader.ForEachCount, 1)
                    : JobsUtility.Schedule(ref scheduleParams);
            }

            eventSystem.AddJobHandleForConsumer <T>(dependsOn);

            return(dependsOn);
        }
Пример #30
0
        public EventListModel(int id,
                              int heatingZoneId,
                              string heatingZoneName,
                              DateTime time,
                              double?temperature,
                              ScheduleMode mode,
                              DateTime?validFrom,
                              DateTime?validTo,
                              bool isActive)
        {
            Id              = id;
            HeatingZoneId   = heatingZoneId;
            HeatingZoneName = heatingZoneName;
            Time            = time;
            Temperature     = temperature != null?temperature?.ToString("N1") + "°C" : null;

            Mode      = mode;
            ValidFrom = validFrom;
            ValidTo   = validTo;
            IsActive  = isActive;
        }
Пример #31
0
        /// <summary>
        /// Starts this <see cref="MicroThread"/> with the specified function.
        /// </summary>
        /// <param name="microThreadFunction">The micro thread function.</param>
        /// <param name="flags">The flags.</param>
        /// <param name="scheduleMode">The schedule mode.</param>
        /// <exception cref="System.InvalidOperationException">MicroThread was already started before.</exception>
        public void Start(Func<Task> microThreadFunction, ScheduleMode scheduleMode = ScheduleMode.Last)
        {
            ScriptId = microThreadFunction.Target.GetType().Name;

            // TODO: Interlocked compare exchange?
            if (Interlocked.CompareExchange(ref state, (int)MicroThreadState.Starting, (int)MicroThreadState.None) != (int)MicroThreadState.None)
                throw new InvalidOperationException("MicroThread was already started before.");

            Action wrappedMicroThreadFunction = async () =>
            {
                try
                {
                    State = MicroThreadState.Running;

                    await microThreadFunction();

                    if (State != MicroThreadState.Running)
                        throw new InvalidOperationException("MicroThread completed in an invalid state.");
                    State = MicroThreadState.Completed;
                }
                catch (OperationCanceledException e)
                {
                    // Exit gracefully on cancellation exceptions
                    SetException(e);
                }
                catch (Exception e)
                {
                    Scheduler.Log.Error("Unexpected exception while executing a micro-thread. Reason: {0}", new object[] {e});
                    SetException(e);
                }
                finally
                {
                    lock (Scheduler.allMicroThreads)
                    {
                        Scheduler.allMicroThreads.Remove(AllLinkedListNode);
                    }
                }
            };

            Action callback = () =>
            {
                SynchronizationContext = new MicroThreadSynchronizationContext(this);
                SynchronizationContext.SetSynchronizationContext(SynchronizationContext);

                wrappedMicroThreadFunction();
            };

            lock (Scheduler.allMicroThreads)
            {
                Scheduler.allMicroThreads.AddLast(AllLinkedListNode);
            }

            ScheduleContinuation(scheduleMode, callback);
        }
Пример #32
0
 public MasterReportDto(int masterrptId, string mastername, string creator, DateTime createddate,
     bool? isscheduled, string melementtype, List<Pair<PageElementType, string>> melementheading, /*bool iscustomheading,*/
     string recipientemail, ScheduleMode schedulemode, int? scheduleday, DateTime? from,
     DateTime? to, List<MasterQuestionnaireDto> masterQ)
 {
     CreatedDate = createddate;
     Creator = creator;
     From = from;
     //IsCustomHeading = iscustomheading;
     IsScheduled = isscheduled;
     MasterName = mastername;
     MasterQ = masterQ;
     MasterRptId = masterrptId;
     MElementHeading = melementheading;
     MElementType = melementtype;
     RecipientEmail = recipientemail;
     ScheduleDay = scheduleday;
     ScheduleMode = schedulemode;
     To = to;
 }
Пример #33
0
 public static string Convert(ScheduleMode mode)
 {
     switch (mode)
     {
         case ScheduleMode.Daily:
             return "d";
         case ScheduleMode.Weekly:
             return "w";
         case ScheduleMode.None:
             return "";
     }
     throw new BugException("unknown schedule mode \"" + mode + "\"");
 }
Пример #34
0
 internal void Reschedule(ScheduleMode scheduleMode, int newPriority)
 {
     lock (Scheduler.scheduledEntries)
     {
         if (ScheduledLinkedListNode.Index != -1)
         {
             Scheduler.scheduledEntries.Remove(ScheduledLinkedListNode);
             ScheduledLinkedListNode.Value.Priority = newPriority;
             Scheduler.Schedule(ScheduledLinkedListNode, scheduleMode);
         }
         else
         {
             ScheduledLinkedListNode.Value.Priority = newPriority;
         }
     }
 }
Пример #35
0
        internal void ScheduleContinuation(ScheduleMode scheduleMode, SendOrPostCallback callback, object callbackState)
        {
            Debug.Assert(callback != null);
            lock (Scheduler.scheduledEntries)
            {
                var node = NewCallback();
                node.SendOrPostCallback = callback;
                node.CallbackState = callbackState;

                if (ScheduledLinkedListNode.Index == -1)
                    Scheduler.Schedule(ScheduledLinkedListNode, scheduleMode);
            }
        }
Пример #36
0
        internal void Schedule(PriorityQueueNode<SchedulerEntry> schedulerEntry, ScheduleMode scheduleMode)
        {
            var nextCounter = SchedulerCounter++;
            if (scheduleMode == ScheduleMode.First)
                nextCounter = -nextCounter;

            schedulerEntry.Value.SchedulerCounter = nextCounter;

            scheduledEntries.Enqueue(schedulerEntry);
        }
Пример #37
0
        internal void ScheduleContinuation(ScheduleMode scheduleMode, Action callback)
        {
            Debug.Assert(callback != null);
            lock (Scheduler.scheduledEntries)
            {
                var node = NewCallback();
                node.MicroThreadAction = callback;

                if (ScheduledLinkedListNode.Index == -1)
                    Scheduler.Schedule(ScheduledLinkedListNode, scheduleMode);
            }
        }
Пример #38
0
		//--------------------------------------------------------------------------------
		/// <summary>
		/// Calculates the next trigger time, based on the current time, the process time, and the schedule mode.
		/// </summary>
		/// <param name="currentTime">The datetime on which to base the calculations</param>
		/// <param name="processTime">For hourly mode, only minutes are used, and for specificInterval mode, it represents the actual amount of time to use, but for all other modes indicates time of day (in all cases, seconds and milliseconds are ignored).</param>
		/// <param name="processMode">The mode with which to process the calculations</param>
		/// <returns></returns>
		public static DateTime CalculateNextTriggerTime(DateTime currentTime, TimeSpan processTime, ScheduleMode scheduleMode)
		{
			if (currentTime == null)
			{
				throw new Exception("Parameter 1 (currentTime) cannot be null");
			}

			// if the processTime object is null, throw an exception - You could 
			// alternately react to a null processTime by creating one with an 
			// appropriate default value, but I figured this would really serve no 
			// purpose in the grand scheme of things, so I didn't do it here.
			if (processTime == null)
			{
				throw new Exception("Parameter 2 (processTime) cannot be null");
			}
			DateTime nextTime = new DateTime();
			nextTime = currentTime;

			switch(scheduleMode)
			{
				case ScheduleMode.Hourly:
					{
						if (nextTime.Minute < processTime.Minutes)
						{
							nextTime = nextTime.AddMinutes(processTime.Minutes - nextTime.Minute);
						}
						else
						{
							// subtract the minutes, seconds, and milliseconds - this allows 
							// us to determine what the last hour was
							nextTime = nextTime.Subtract(new TimeSpan(0, 0, nextTime.Minute, nextTime.Second, nextTime.Millisecond));

							// add an hour and the number of minutes 
							nextTime = nextTime.Add(new TimeSpan(0, 1, processTime.Minutes, 0, 0));
						}
					}
					break;

				case ScheduleMode.Daily:
					{
						// subtract the hour, minutes, seconds, and milliseconds (essentially, makes it midnight of the current day)
						nextTime = nextTime.Subtract(new TimeSpan(0,nextTime.Hour,nextTime.Minute,nextTime.Second,nextTime.Millisecond));

						// add a day, and the number of hours:minutes after midnight
						nextTime = nextTime.Add(new TimeSpan(1,processTime.Hours,processTime.Minutes,0,0));
					}
					break;

				case ScheduleMode.Weekly:
					{
						int daysToAdd = 0;

						// get the number of the week day
						int dayNumber = (int)nextTime.DayOfWeek;

						// if the process day isn't today (should only happen when the service starts)
						if (dayNumber == processTime.Days)
						{
							// add 7 days
							daysToAdd = 7;
						}
						else
						{
							// determine where in the week we are
							// if the day number is > than the specified day
							if (dayNumber > processTime.Days)
							{
								// subtract the day number from 7 to get the number of days to add
								daysToAdd = 7 - dayNumber;
							}
							else
							{
								// otherwise, subtract the day number from the specified day
								daysToAdd = processTime.Days - dayNumber;
							}
						}

						// add the days
						nextTime = nextTime.AddDays(daysToAdd);

						// get rid of the seconds/milliseconds
						nextTime = nextTime.Subtract(new TimeSpan(0, nextTime.Hour, nextTime.Minute, nextTime.Second, nextTime.Millisecond));

						// add the specified time of day
						nextTime = nextTime.Add(new TimeSpan(0, processTime.Hours, processTime.Minutes, 0, 0));
					}
					break;

				case ScheduleMode.FirstDayOfMonth:
					{
						// detrmine how many days in the month
						int daysThisMonth = DaysInMonth(nextTime);

						// for ease of typing
						int today = nextTime.Day;

						// if today is the first day of the month
						if (today == 1)
						{
							// simply add the number of days in the month
							nextTime = nextTime.AddDays(daysThisMonth);
						}
						else
						{
							// otherwise, add the remaining days in the month
							nextTime = nextTime.AddDays((daysThisMonth - today) + 1);
						}
						// get rid of the seconds/milliseconds
						nextTime = nextTime.Subtract(new TimeSpan(0,nextTime.Hour,nextTime.Minute,nextTime.Second,nextTime.Millisecond));

						// add the specified time of day
						nextTime = nextTime.Add(new TimeSpan(0, processTime.Hours, processTime.Minutes, 0, 0));
					}
					break;

				case ScheduleMode.LastDayOfMonth:
					{
						// detrmine how many days in the month
						int daysThisMonth = DaysInMonth(nextTime);

						// for ease of typing
						int today = nextTime.Day;

						// if this is the last day of the month
						if (today == daysThisMonth)
						{
							// add the number of days for the next month
							int daysNextMonth = DaysInMonth(nextTime.AddDays(1));
							nextTime = nextTime.AddDays(daysNextMonth);
						}
						else
						{
							// otherwise, add the remaining days for this month
							nextTime = nextTime.AddDays(daysThisMonth - today);
						}

						// get rid of the seconds/milliseconds
						nextTime = nextTime.Subtract(new TimeSpan(0, nextTime.Hour, nextTime.Minute, nextTime.Second, nextTime.Millisecond));

						// add the specified time of day
						nextTime = nextTime.Add(new TimeSpan(0, processTime.Hours, processTime.Minutes, 0, 0));
					}
					break;

				// The processTime.Day property indicates what day of the month to 
				// schedule, and the hour/minute properties indicate the time of the day 
				case ScheduleMode.DayOfMonth:
					{
						// account for leap year
						// assume we don't have a leap day 
						int leapDay = 0;
						// if it's february, and a leap year and the day is 29
						if (nextTime.Month == 2 && !IsLeapYear(nextTime) && processTime.Days == 29)
						{
							// we have a leap day
							leapDay = 1;
						}

						// If the current day is earlier in the month than the desired day,
						// calculate how many days there are between the two
						int daysToAdd = 0;
						// if the current day is earlier than the desired day
						if (nextTime.Day < processTime.Days)
						{
							// add the difference (less the leap day)
							daysToAdd = processTime.Days - nextTime.Day - leapDay;
						}
						else
						{
							// otherwise, add the days not yet consumed (less the leap day)
							daysToAdd = (DaysInMonth(nextTime) - nextTime.Day) + processTime.Days - leapDay;
						}
						// add the calculated days
						nextTime = nextTime.AddDays(daysToAdd);

						// get rid of the seconds/milliseconds
						nextTime = nextTime.Subtract(new TimeSpan(0, nextTime.Hour, nextTime.Minute, nextTime.Second, nextTime.Millisecond));

						// add the specified time of day
						nextTime = nextTime.Add(new TimeSpan(0, processTime.Hours, processTime.Minutes, 0, 0));
					}
					break;

				case ScheduleMode.SpecificInterval:
					{
						// if we're past the 30-second mark, add a minute to the current time
						if (nextTime.Second >= 30)
						{
							nextTime = nextTime.AddSeconds(60 - nextTime.Second);
						}

						// since we don't care about seconds or milliseconds, zero these items out
						nextTime = nextTime.Subtract(new TimeSpan(0, 0, 0, nextTime.Second, nextTime.Millisecond));

						// now, we add the process time
						nextTime = nextTime.Add(processTime);
					}
					break;
			}

			// and subtract the seconds and milliseconds, just in case they were specified in the process time 
			nextTime = nextTime.Subtract(new TimeSpan(0, 0, 0, nextTime.Second, nextTime.Millisecond));

			return nextTime;
		}
Пример #39
0
 public MasterReportDto(string mastername, string creator, DateTime createddate, bool isscheduled, string melementtype, List<Pair<PageElementType, string>> melementheading, /*bool iscustomheading, */string recipientemail, ScheduleMode schedulemode, int scheduleday, DateTime from, DateTime to, List<MasterQuestionnaireDto> masterQ)
     : this(TransientId, mastername, creator, createddate, isscheduled, melementtype, melementheading, /*iscustomheading, */recipientemail, schedulemode, scheduleday, from, to, masterQ)
 {
 }