示例#1
0
        public IDisposable Schedule(TimeSpan dueTime, Action action)
        {
            var dueInMilliseconds = dueTime.TotalMilliseconds;
            int insertionIndex    = 0;

            for (insertionIndex = 0; insertionIndex < ScheduledActions.Count; insertionIndex++)
            {
                if (ScheduledActions[insertionIndex].DueInMilliseconds > dueInMilliseconds)
                {
                    break;
                }
            }

            var scheduledAction = new ScheduledAction
            {
                DueInMilliseconds = dueInMilliseconds,
                Action            = action
            };

            ScheduledActions.Insert(insertionIndex, scheduledAction);

            return(new AnonymousDisposable(() => {
                ScheduledActions.Remove(scheduledAction);
            }));
        }
示例#2
0
        /// <inheritdoc/>
        public void Schedule(ScheduledAction subscriber, ScheduleOptions options)
        {
            // Check for existing subscription
            var sub = GetSubscription(subscriber, false);

            if (sub != null)
            {
                throw new InvalidOperationException(Strings.AlreadySubscribed);
            }

            // Make sure lookup exists
            if (subscriptions == null)
            {
                subscriptions = new Lookup <ScheduledAction>();
            }

            // Threadsafe
            lock (subscriptions)
            {
                // Add lookup
                subscriptions[subscriber] = new Subscription()
                {
                    Options = options
                };
            }

            // Ensure interval
            EnsureMinReportInterval(options.UpdateInterval);

            // Start?
            QueryStart();
        }
示例#3
0
        public async Task <List <ScheduledAction> > GetScheduledActions()
        {
            var ret             = new List <ScheduledAction>();
            var lstSettingItems = await helper.GetScheduledActionSettingItems();

            HashSet <string> actionNames = new HashSet <string>();

            foreach (var setting in lstSettingItems)
            {
                actionNames.Add(setting.ResourceName);
            }
            foreach (string actionName in actionNames)
            {
                ScheduledAction action = new ScheduledAction();
                action.Name = actionName;
                foreach (var prop in typeof(ScheduledAction).GetProperties())
                {
                    var valueItem = lstSettingItems.Find
                                        (o => o.OptionName == prop.Name && o.ResourceName == actionName);
                    if (valueItem != null)
                    {
                        prop.SetValue(action, valueItem.Value);
                    }
                }
                ret.Add(action);
            }

            return(ret);
        }
示例#4
0
        public static void ExecuteUpdate(SshClient sshClient, ScheduledAction scheduledAction)
        {
            var resultKey = $"{scheduledAction.FreeBsdSessionName} finished with result ";

            if (!Screen.Exists(sshClient, scheduledAction))
            {
                Screen.StartScheduledActionCommand(sshClient, scheduledAction, $"PAGER=cat sudo freebsd-update fetch ; sudo freebsd-update install ; echo {resultKey}$?");
            }

            while (Screen.Exists(sshClient, scheduledAction))
            {
                Thread.Sleep(10000);
            }

            var success = sshClient.CreateCommand($"tail -n 10 {scheduledAction.FreeBsdLogPath} | grep \"{resultKey}\"").Execute().Replace(resultKey, "").Trim() == "0";

            var fullOutput = sshClient.CreateCommand($"cat {scheduledAction.FreeBsdLogPath}").Execute();

            Log.Information($"Scheduled action {scheduledAction.Id} full output: {fullOutput}");

            if (!success)
            {
                throw new ApplicationException($"System update of {scheduledAction.ManagedSystem.Name} was unsuccessful.");
            }
        }
示例#5
0
        public IScheduledAction Schedule(Action action, TimeSpan period)
        {
            var scheduledAction = new ScheduledAction(action, UtcNow + period);

            _scheduledActions.Add(scheduledAction);
            return(scheduledAction);
        }
        public void CreateReminder(PlannerSearch search, int?index, DateTime dateTime, string spoor, DateTime reminderTime)
        {
            try
            {
                string url = string.Format("/Views/Reisadvies.xaml?id={0}&index={1}", search.Id, index);

                ScheduledAction oldReminder = ScheduledActionService.Find(url);
                if (oldReminder != null)
                {
                    ScheduledActionService.Remove(url);
                }

                Reminder newReminder = new Reminder(url)
                {
                    BeginTime      = reminderTime,
                    RecurrenceType = RecurrenceInterval.None,
                    NavigationUri  = new Uri(url, UriKind.Relative),
                    Title          = AppResources.ReminderAppTitle,
                    Content        = string.Format(AppResources.ReminderServiceFormat, search.NaarStation.Name, dateTime.ToString("HH:mm", CultureInfo.InvariantCulture), search.VanStation.Name, spoor),
                };;

                ScheduledActionService.Add(newReminder);
            }
            catch { }
        }
示例#7
0
        public void TestAddActionRuns()
        {
            bool ran = false;

            Instant due = TimeHelpers.Clock.Now + Duration.FromMilliseconds(100);

            Assert.IsTrue(due > TimeHelpers.Clock.Now);

            ScheduledAction action = Scheduler.Add(() => { ran = true; }, new OneOffSchedule(due));

            Assert.IsTrue(due > TimeHelpers.Clock.Now);

            Assert.IsNotNull(action);
            Assert.IsTrue(action.Enabled);
            Assert.AreEqual(Scheduler.DefaultMaximumHistory, action.MaximumHistory);
            Assert.AreEqual(Scheduler.DefaultMaximumDuration, action.MaximumDuration);
            Thread.Sleep(200);
            Assert.IsTrue(ran);
            Assert.AreEqual(1, action.History.Count());

            ScheduledActionResult history = action.History.FirstOrDefault();

            Assert.IsNotNull(history);
            Assert.IsFalse(history.Cancelled);
            Assert.IsNull(history.Exception);
            Assert.AreEqual(due, history.Due);
            Assert.IsTrue(history.Due <= history.Started);
        }
示例#8
0
文件: Packages.cs 项目: nono3551/paco
        public static void UpdatePackages(SshClient sshClient, ScheduledAction scheduledAction)
        {
            var nscdStop  = "";
            var nscdStart = "";

            var resultKey = $"{scheduledAction.FreeBsdSessionName} finished with result ";

            if ("sudo /usr/sbin/service nscd status".ExecuteCommand(sshClient).Response.Contains("nscd is running as pid"))
            {
                nscdStart = " ; sudo /usr/sbin/service nscd start";
                nscdStop  = "sudo /usr/sbin/service nscd stop ; ";
            }

            if (!Screen.Exists(sshClient, scheduledAction))
            {
                Screen.StartScheduledActionCommand(sshClient, scheduledAction, $"{nscdStop} PAGER=cat echo \"y\" | sudo portmaster -ad ; echo {resultKey}$? {nscdStart}");
            }

            while (Screen.Exists(sshClient, scheduledAction))
            {
                Thread.Sleep(10000);
            }

            var success = sshClient.CreateCommand($"tail -n 100 {scheduledAction.FreeBsdLogPath} | grep \"{resultKey}\"").Execute().Replace(resultKey, "").Trim() == "0";

            var fullOutput = sshClient.CreateCommand($"cat {scheduledAction.FreeBsdLogPath}").Execute();

            Log.Information($"Scheduled action {scheduledAction.Id} full output: {fullOutput}");

            if (!success)
            {
                throw new ApplicationException($"Packages action execution of {scheduledAction.ManagedSystem.Name} was unsuccessful.");
            }
        }
示例#9
0
        public void ExecuteScheduledAction(ScheduledAction update)
        {
            Logger.LogInformation("Starting scheduled action {actionId}.", update.Id);

            ExecuteWorkWithSystem(update.ManagedSystem, managedSystem =>
            {
                if (update.ScheduledActionStatus == ScheduledActionStatus.Queued)
                {
                    update.ScheduledActionStatus = ScheduledActionStatus.Started;
                    update.StartedAt             = DateTime.Now;
                }

                DbContextFactory.Upsert(update);

                GetDistributionManager(managedSystem).ExecuteScheduledAction(update);
            }, managedSystem =>
            {
                update.ScheduledActionStatus = ScheduledActionStatus.Successful;
                DbContextFactory.Upsert(update);
            }, managedSystem =>
            {
                update.ScheduledActionStatus = ScheduledActionStatus.Failure;
                DbContextFactory.Upsert(update);
            });
        }
示例#10
0
        public void Should_run_the_action_until_disabled()
        {
            Fiber     fiber     = new ThreadPoolFiber();
            Scheduler scheduler = new TimerScheduler(new ThreadPoolFiber());

            Stopwatch elapsed = Stopwatch.StartNew();

            int count  = 0;
            var called = new Future <int>();
            var failed = new Future <bool>();

            ScheduledAction scheduledAction = null;

            scheduledAction = scheduler.Schedule(TimeSpan.Zero, 100.Milliseconds(), fiber, () =>
            {
                count++;
                if (count == 10)
                {
                    called.Complete(count);
                    scheduledAction.Cancel();
                }
                else if (count > 10)
                {
                    failed.Complete(true);
                }
            });

            called.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();

            elapsed.Stop();

            failed.WaitUntilCompleted(200.Milliseconds()).ShouldBeFalse();

            Trace.WriteLine("Time Period: " + elapsed.ElapsedMilliseconds);
        }
示例#11
0
        /// <inheritdoc/>
        public void Resume(ScheduledAction subscriber)
        {
            var s = GetSubscription(subscriber);

            s.IsSuspended = false;
            EnsureMinReportInterval(s.Options.UpdateInterval);
        }
示例#12
0
 private void ScheduleInFuture(ScheduledAction scheduledAction)
 {
     lock (_scheduledActions)
     {
         _scheduledActions.Add(scheduledAction);
     }
 }
示例#13
0
        public void TestAddActionCancel()
        {
            bool            ran      = false;
            Instant         due      = TimeHelpers.Clock.Now + Duration.FromMilliseconds(100);
            Duration        duration = Duration.FromMilliseconds(20);
            ScheduledAction action   = Scheduler.Add(
                () =>
            {
                ran = true;
                // This needs to sleep longer than the max duration to ensure it will be cancelled
                Thread.Sleep((int)duration.TotalMilliseconds() * 2);
            },
                new OneOffSchedule(due),
                maximumDuration: duration);

            Assert.IsNotNull(action);
            Assert.IsTrue(action.Enabled);
            Assert.AreEqual(Scheduler.DefaultMaximumHistory, action.MaximumHistory);
            Assert.AreEqual(duration, action.MaximumDuration);
            Thread.Sleep(200);
            Assert.IsTrue(ran);
            Assert.AreEqual(1, action.History.Count());

            ScheduledActionResult history = action.History.FirstOrDefault();

            Assert.IsNotNull(history);
            Assert.IsTrue(history.Cancelled);
            Assert.IsNull(history.Exception);
            Assert.AreEqual(due, history.Due);
            Assert.IsTrue(history.Due <= history.Started);
        }
示例#14
0
        // Constructor
        public MainPage()
        {
            IScheduler scheduler = Scheduler.Dispatcher;

            scheduler.Schedule(() =>
            {
                InitializeComponent();
                SystemTray.SetOpacity(this, 0.0);
                SetRefreshImage();
                if (!(App.isoSettings.Contains("UpComing")))
                {
                    App.isoSettings.Add("UpComing", "");
                }
                if (!(App.isoSettings.Contains("FinalKey")))
                {
                    App.isoSettings.Add("FinalKey", "");
                }

                RefreshTileTask();
            });
            DataContext = App.MainViewModel;



#if DEBUG
            ScheduledAction action = ScheduledActionService.Find("CanucksNewsScheduler");
            if (action != null)
            {
                ScheduledActionService.LaunchForTest("CanucksNewsScheduler", TimeSpan.FromSeconds(1));
            }
            #endif
        }
示例#15
0
        public IDisposable ScheduleOne(Action action, TimeSpan delay)
        {
            var scheduledAction = new ScheduledAction(action, delay, delay, 1);

            ScheduleInFuture(scheduledAction);

            return(scheduledAction);
        }
示例#16
0
 /// <summary>
 ///   On the next frame, an action is scheduled to execute.
 /// </summary>
 /// <param name="action">The action to execute.</param>
 /// <param name="framesUntilExecution">
 ///   The number of frames until the action executes.
 /// </param>
 /// <returns>
 ///   A <see cref="ScheduledAction" /> reference for the action to be executed.
 /// </returns>
 /// <remarks>
 ///   As this action is scheduled on the next frame, one frame is
 ///   subtracted from the <paramref name="framesUntilExecution" /> argument.
 /// </remarks>
 public ScheduledAction ScheduleActionOnNextFrame(Action action, int framesUntilExecution)
 {
     // Subtract one frame from the frames until execution because we have
     // to wait until the next frame to actually schedule the action.
     var result = new ScheduledAction(action, framesUntilExecution - 1);
     actionsToScheduleNextFrame.Add(result);
     return result;
 }
示例#17
0
        public IDisposable ScheduleInterval(Action action, TimeSpan dueTime, TimeSpan period)
        {
            var scheduledAction = new ScheduledAction(action, period, dueTime);

            ScheduleInFuture(scheduledAction);

            return(scheduledAction);
        }
示例#18
0
        public void CreateButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                string reminderName = "My reminder " + i;

                Reminder reminder = new Reminder(reminderName);
                // NOTE: setting the Title property is supported for reminders
                reminder.Title   = "My reminders .... " + i;
                reminder.Content = "My reminders .... My reminders ...." + i;

                //NOTE: the value of BeginTime must be after the current time
                //set the BeginTime time property in order to specify when the reminder should be shown
                reminder.BeginTime = DateTime.Now.AddSeconds(5.0D + i);

                // NOTE: ExpirationTime must be after BeginTime
                // the value of the ExpirationTime property specifies when the schedule of the reminder expires
                // very useful for recurring reminders, ex:
                // show reminder every day at 5PM but stop after 10 days from now
                reminder.ExpirationTime = reminder.BeginTime.AddSeconds(5.0 + i);
                reminder.RecurrenceType = RecurrenceInterval.Daily;

                // you can set a navigation uri that is passed to the application when it is launched from the reminder
                //reminder.NavigationUri = navigationUri;
                reminder.NavigationUri = new Uri("/View/FirstPage.xaml", UriKind.Relative);

                ScheduledAction sa = ScheduledActionService.Find(reminderName);
                if (sa == null)
                {
                    try
                    {
                        ScheduledActionService.Add(reminder);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("Can not create the reminder: " + ex.Message);
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("A reminder is set already.");
                    System.Windows.MessageBox.Show("A reminder is set already.");
                }
            }

            IEnumerable <Reminder> reminders = ScheduledActionService.GetActions <Reminder>();

            if (reminders != null)
            {
                foreach (Reminder re in reminders)
                {
                    System.Diagnostics.Debug.WriteLine("The name of the reminder: " + re.Name);
                    System.Diagnostics.Debug.WriteLine("The reminder is scheduled: " + re.IsScheduled);
                    System.Diagnostics.Debug.WriteLine("The tile of the reminder: " + re.Title);
                }
                System.Windows.MessageBox.Show("Reminders are scheduled!");
            }
        }
示例#19
0
    /// <summary>
    /// Updates all ScheduledAcions in the schedule and the queue.
    /// </summary>
    public void Update()
    {
        _inUpdate = true;
        long deltaTicks = Math.Max(0, _program.Runtime.TimeSinceLastRun.Ticks / ClockTicksPerGameTick);

        if (_firstRun)
        {
            if (_ignoreFirstRun)
            {
                deltaTicks = 0;
            }
            _firstRun = false;
        }

        _actionsToDispose.Clear();
        foreach (ScheduledAction action in _scheduledActions)
        {
            CurrentTicksSinceLastRun = action.TicksSinceLastRun + deltaTicks;
            CurrentTimeSinceLastRun  = action.TimeSinceLastRun + deltaTicks * TickDurationSeconds;
            action.Update(deltaTicks);
            if (action.JustRan && action.DisposeAfterRun)
            {
                _actionsToDispose.Add(action);
            }
        }

        if (_actionsToDispose.Count > 0)
        {
            _scheduledActions.RemoveAll((x) => _actionsToDispose.Contains(x));
        }

        if (_currentlyQueuedAction == null)
        {
            // If queue is not empty, populate current queued action
            if (_queuedActions.Count != 0)
            {
                _currentlyQueuedAction = _queuedActions.Dequeue();
            }
        }

        // If queued action is populated
        if (_currentlyQueuedAction != null)
        {
            _currentlyQueuedAction.Update(deltaTicks);
            if (_currentlyQueuedAction.JustRan)
            {
                // Set the queued action to null for the next cycle
                _currentlyQueuedAction = null;
            }
        }
        _inUpdate = false;

        if (_actionsToAdd.Count > 0)
        {
            _scheduledActions.AddRange(_actionsToAdd);
            _actionsToAdd.Clear();
        }
    }
示例#20
0
 private void FillEventByItem()
 {
     _reminder = _item.Reminder;
     if (_reminder != null)
     {
         StartDate = _reminder.BeginTime;
         StartTime = _reminder.BeginTime;
     }
 }
示例#21
0
        private void HandleIsEnabledStateChanged()
        {
            _autoEnableAction?.Cancel();

            if (!Settings.IsEnabled)
            {
                _autoEnableAction = ScheduledAction.Schedule(Settings.AutoEnableAfter, () => _settingsService.SetComponentEnabledState(this, true));
            }
        }
示例#22
0
 /// <summary>
 /// If interrupts are allowed, stops the current ScheduledAction and runs this action. Once complete, the thread will continue through the queue like normal but the interrupted action will never complete.
 /// </summary>
 /// <param name="action">The action to interrupt with.</param>
 public void Interrupt(ScheduledAction action, params object[] args)
 {
     if (!allowInterrupts)
     {
         throw new InvalidOperationException("This ScheduledThread does not allow interrupts.");
     }
     currentInterrupt.Push(new ActionEntry(action, args));
     skip();
 }
示例#23
0
        public void ScheduledActionEmail(ScheduledAction scheduledAction)
        {
            var body =
                $"<p>Scheduled action's status was changed.</p><table class=\"table\"><tbody><tr><td>New status</td><td>{scheduledAction.ScheduledActionStatus}</td></tr><tr><td>Action type</td><td>{scheduledAction.ScheduledActionType}</td></tr><tr><td>System name</td><td>{scheduledAction.ManagedSystem.Name}</td></tr><tr><td>Time</td><td>{DateTime.UtcNow}</td></tr></tbody></table>";

            var subject = $"[ACTION-{scheduledAction.ScheduledActionType}-{scheduledAction.ScheduledActionStatus}] {scheduledAction.ManagedSystem.Name}";

            QueueEmail(subject, body, GetRecipientsForScheduledAction(scheduledAction));
        }
        public void DeleteReminder(string name)
        {
            ScheduledAction oldReminder = ScheduledActionService.Find(name);

            if (oldReminder != null)
            {
                ScheduledActionService.Remove(name);
            }
        }
        static private void GetSubscriber(Delegate subscriber, out ScheduledAsyncAction a, out ScheduledAction s)
        {
            a = subscriber as ScheduledAsyncAction;
            s = subscriber as ScheduledAction;

            if ((a == null) && (s == null))
            {
                throw new InvalidOperationException(Strings.InvalidSubscriberType);
            }
        }
        public ScheduledAction CreatePlantAction(Plant plant, int amountOfWaterInMl, DateTime scheduledDate)
        {
            var newAction = new ScheduledAction()
            {
                Plant                    = plant,
                ScheduledDate            = scheduledDate,
                AmountOfWaterMilliliters = amountOfWaterInMl
            };

            return(newAction);
        }
示例#27
0
 /// <summary>
 /// Adds a ScheduledAction to the schedule. All actions are updated each update call.
 /// </summary>
 public void AddScheduledAction(ScheduledAction scheduledAction)
 {
     if (!_inUpdate)
     {
         _scheduledActions.Add(scheduledAction);
     }
     else
     {
         _actionsToAdd.Add(scheduledAction);
     }
 }
示例#28
0
        static void OnDropDownClosed(object sender, EventArgs e)
        {
            ToolStripDropDownItem   dropDown = (ToolStripDropDownItem)sender;
            Queue <ScheduledAction> actions  = scheduledActions[dropDown];

            while (actions.Any())
            {
                ScheduledAction scheduledAction = actions.Dequeue();
                scheduledAction.action(dropDown.DropDownItems, scheduledAction.item);
            }
        }
示例#29
0
        public static ScheduledAction ToEntity(this PlantsActionDto dto)
        {
            ScheduledAction action = new ScheduledAction()
            {
                PlantId                  = dto.PlantId,
                ScheduledDate            = dto.ScheduledDate,
                AmountOfWaterMilliliters = dto.AmountOfWaterMilliliters,
            };

            return(action);
        }
示例#30
0
 public void ExecuteScheduledAction(ScheduledAction scheduledAction)
 {
     using var client = SshManager.CreateSshClient(System);
     if (scheduledAction.ScheduledActionType == ScheduledActionType.Packages)
     {
         Packages.UpdatePackages(client, scheduledAction);
     }
     else if (scheduledAction.ScheduledActionType == ScheduledActionType.System)
     {
         SystemUpdate.ExecuteUpdate(client, scheduledAction);
     }
 }
示例#31
0
 /// <summary>
 ///   Cancels a scheduled action.
 /// </summary>
 /// <param name="action">The action to cancel.</param>
 /// <returns>
 ///   True if the action has been cancelled, false if the action wasn't
 ///   scheduled at all.
 /// </returns>
 public bool CancelScheduledAction(ScheduledAction action)
 {
     if (scheduledActions.Contains(action))
     {
         scheduledActions.Remove(action);
         return true;
     }
     else
     {
         return actionsToScheduleNextFrame.Remove(action);
     }
 }
示例#32
0
 /// <summary>
 /// Schedules a ScheduledAction to be run after all of the currently scheduled ScheduledActions have completed.
 /// </summary>
 /// <param name="action">The action to schedule.</param>
 public void Queue(ScheduledAction action, params object[] args)
 {
     if (clearingRequests.IsEmpty)
     {
         bool wasEmpty = entries.IsEmpty;
         entries.Enqueue(new ActionEntry(action, args));
         if (wasEmpty)
         {
             waitHandle.Set();
         }
     }
 }
示例#33
0
        /// <summary>
        /// Initializes a new <see cref="ObservableEvent{TSender, TResult}"/>.
        /// </summary>
        /// <param name="firstAdded">
        /// A <see cref="ScheduledAction"/> that will be called when the first subscriber is added.
        /// </param>
        /// <param name="lastRemoved">
        /// A <see cref="ScheduledAction"/> that will be called when the last subscriber is removed.
        /// </param>
        public ObservableEvent(ScheduledAction firstAdded, ScheduledAction lastRemoved = null) : this()
        {
            // Validate
            if ((firstAdded == null) && (lastRemoved == null))
            {
                throw new ArgumentNullException($"{nameof(firstAdded)} and {nameof(lastRemoved)} cannot both be null");
            }

            // Store
            this.firstAdded  = firstAdded;
            this.lastRemoved = lastRemoved;
        }
示例#34
0
 private void Remove(ScheduledAction scheduledAction)
 {
     lock (_actions)
     {
         var pos = _actions.BinarySearch(scheduledAction);
         _actions.RemoveAt(pos);
         scheduledAction.Release();
         if(pos==0)
         {
             _resetEvent.Set();
         }
     }
 }
        /// <summary>
        /// Creates a PollingFileSystemEventProducer
        /// </summary>		
        /// <param name="directory">The directory to watch</param>
        /// <param name="channel">The channel where events should be sent</param>
        /// <param name="scheduler">Event scheduler</param>
        /// <param name="fiber">Fiber to schedule on</param>
        /// <param name="checkInterval">The maximal time between events or polls on a given file</param>
        /// <param name="checkSubDirectory">Indicates if subdirectorys will be checked or ignored</param>
        public PollingFileSystemEventProducer(string directory, UntypedChannel channel, Scheduler scheduler, Fiber fiber,
            TimeSpan checkInterval, bool checkSubDirectory)
        {
            _directory = directory;
            _channel = channel;
            _fiber = fiber;
            _hashes = new Dictionary<string, Guid>();
            _scheduler = scheduler;
            _checkInterval = checkInterval;

            _scheduledAction = scheduler.Schedule(3.Seconds(), _fiber, HashFileSystem);

            ChannelAdapter myChannel = new ChannelAdapter();

            _connection = myChannel.Connect(connectionConfigurator =>
            {
                connectionConfigurator.AddConsumerOf<FileSystemChanged>().UsingConsumer(HandleFileSystemChangedAndCreated);
                connectionConfigurator.AddConsumerOf<FileSystemCreated>().UsingConsumer(HandleFileSystemChangedAndCreated);
                connectionConfigurator.AddConsumerOf<FileSystemRenamed>().UsingConsumer(HandleFileSystemRenamed);
                connectionConfigurator.AddConsumerOf<FileSystemDeleted>().UsingConsumer(HandleFileSystemDeleted);
            });

            _fileSystemEventProducer = new FileSystemEventProducer(directory, myChannel, checkSubDirectory);
        }
示例#36
0
        private void Remove(ScheduledAction scheduledAction)
        {
            if (scheduledAction.PrevAction != null)
            {
            scheduledAction.PrevAction.NextAction = scheduledAction.NextAction;
            }
            else
            {
            _first = scheduledAction.NextAction;
            }

            if (scheduledAction.NextAction != null)
            {
            scheduledAction.NextAction.PrevAction = scheduledAction.PrevAction;
            }

            scheduledAction.PrevAction = null;
            scheduledAction.NextAction = null;
        }
示例#37
0
 public RodViewModel(string rodName, Brush color)
 {
     RodName = rodName;
     Color = color;
     AlarmTime = 2;
     SetAlarmCommand = new ActionCommand(new Action(SetAlarm));
     alarm = ScheduledActionService.Find(rodName);
     if (alarm == null)
         ResetAlarmCommand = new DummyDisabled();
     else
         ResetAlarmCommand = new ActionCommand(ResetAlarm);
     DispatcherTimer newTimer = new DispatcherTimer();
     newTimer.Interval = TimeSpan.FromSeconds(1);
     newTimer.Tick += OnTimerTick;
     newTimer.Start();
 }
示例#38
0
 public void OnRodExpired()
 {
     if (alarm != null)
     {
         ScheduledActionService.Remove(alarm.Name);
         alarm = null;
         if (PropertyChanged != null)
         {
             PropertyChanged(this, new PropertyChangedEventArgs("ElapsedTime"));
         }
     }
 }
示例#39
0
 void ResetAlarm()
 {
     this.alarm = ScheduledActionService.Find(RodName);
     if (this.alarm != null)
     {
         ScheduledActionService.Remove(this.alarm.Name);
         this.alarm = null;
     }
 }
示例#40
0
        void SetAlarm()
        {
            MessageBoxResult resul=MessageBox.Show(String.Format("Do you whant reset alarm on:{0} hours", AlarmTime), "Reset Alarm", MessageBoxButton.OKCancel);
            if (resul == MessageBoxResult.Cancel)
                return;
            this.alarm = ScheduledActionService.Find(RodName);
            if (this.alarm != null)
            {
                ScheduledActionService.Remove(this.alarm.Name);
                this.alarm = null;
            }

            Alarm alarm;
            alarm = new Alarm(RodName);
            // NOTE: setting the Title property is not supported for alarms
            //alarm.Title = this.txtTitle.Text;
            alarm.Content = RodName + " timer expired";
            double seconds = AlarmTime *3600;

            //NOTE: the value of BeginTime must be after the current time
            //set the BeginTime time property in order to specify when the alarm should be shown
            alarm.BeginTime = DateTime.Now.AddSeconds(seconds);

            // NOTE: ExpirationTime must be after BeginTime
            // the value of the ExpirationTime property specifies when the schedule of the alarm expires
            // very useful for recurring alarms, ex:
            // show alarm every day at 5PM but stop after 10 days from now
            alarm.ExpirationTime = alarm.BeginTime.AddSeconds(5.0);

            alarm.RecurrenceType = RecurrenceInterval.None;
            alarm.Sound = new Uri("/Ringtones/Alarm.mp3", UriKind.Relative);
            ScheduledActionService.Add(alarm);
            this.alarm = alarm;
            ResetAlarmCommand = new ActionCommand(new Action(ResetAlarm));
            if(PropertyChanged!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("ElapsedTime"));
                PropertyChanged(this, new PropertyChangedEventArgs("ResetAlarmCommand"));
            }
        }
示例#41
0
 /// <summary>
 ///   Schedules an action to occur in a certain number of frames.
 /// </summary>
 /// <param name="action">The action to execute.</param>
 /// <param name="framesUntilExecution">
 ///   The number of frames until the action is executed.
 /// </param>
 public ScheduledAction ScheduleAction(Action action, int framesUntilExecution)
 {
     var result = new ScheduledAction(action, framesUntilExecution);
     scheduledActions.Add(result);
     return result;
 }
        void HashFileSystem()
        {
            try
            {
                Dictionary<string, Guid> newHashes = new Dictionary<string, Guid>();

                ProcessDirectory(newHashes, _directory);

                // process all the new hashes found
                newHashes.ToList().ForEach(x => HandleHash(x.Key, x.Value));

                // remove any hashes we couldn't process
                _hashes.Where(x => !newHashes.ContainsKey(x.Key)).ToList().ConvertAll(x => x.Key).ForEach(RemoveHash);
            }
            finally
            {
                _scheduledAction = _scheduler.Schedule(_checkInterval, _fiber, HashFileSystem);
            }
        }
示例#43
0
        /// <summary>
        /// Sets a synchronous update action to be called by the scheduler.
        /// </summary>
        /// <param name="updateAction">
        /// The synchronous update action.
        /// </param>
        public void SetUpdateAction(ScheduledAction updateAction)
        {
            // Validate
            if (updateAction == null) throw new ArgumentNullException("updateAction");
            if (scheduled) { throw new InvalidOperationException(Strings.ExistingUpdateAction); }

            // Store
            this.asyncUpdateAction = null;
            this.updateAction = updateAction;
        }
示例#44
0
        private void QueueInternal(ScheduledAction scheduledAction)
        {
            lock (_actions)
            {
                var pos = _actions.BinarySearch(scheduledAction);
                pos = pos >= 0 ? pos : ~pos;
                _actions.Insert(pos, scheduledAction);

                if (pos == 0)
                {
                    _resetEvent.Set();
                }
            }
        }
示例#45
0
 private void Cancel(ScheduledAction scheduledAction)
 {
     lock (_lock)
     {
     Remove(scheduledAction);
     }
 }
示例#46
0
 private void DoSchedule(ScheduledAction scheduledAction)
 {
     lock (_lock)
     {
     var predecessor = TryFindPredecessor(scheduledAction, startWith: _first);
     MoveBehind(scheduledAction, predecessor);
     }
 }
示例#47
0
        private void MoveBehind(ScheduledAction scheduledAction, ScheduledAction predecessor)
        {
            if (predecessor != null)
            {
            scheduledAction.PrevAction = predecessor;
            scheduledAction.NextAction = predecessor.NextAction;
            if (predecessor.NextAction != null)
            {
                predecessor.NextAction.PrevAction = scheduledAction;
            }
            predecessor.NextAction = scheduledAction;
            }
            else
            {
            if (_first != null)
            {
                _first.PrevAction = scheduledAction;
            }

            scheduledAction.NextAction = _first;
            _first = scheduledAction;
            }
        }
示例#48
0
        private ScheduledAction TryFindPredecessor(ScheduledAction scheduledAction, ScheduledAction startWith)
        {
            ScheduledAction predecessor = null;
            for (var action = startWith; action != null; action = action.NextAction)
            {
            if (action.NextExecutionEpoch >= scheduledAction.NextExecutionEpoch)
            {
                break;
            }

            predecessor = action;
            }
            return predecessor;
        }
示例#49
0
        public ICancelable Schedule(Action<DateTime, float> action, TimeSpan timeSpan, bool recurring = false, TimeSpan delay = default(TimeSpan))
        {
            double nextExecutionEpoch;
            lock (_lock)
            {
            nextExecutionEpoch = _epochTime + timeSpan.TotalSeconds + delay.TotalSeconds;
            }

            var scheduledAction = new ScheduledAction(this, action)
            {
            Interval           = timeSpan,
            Recurring          = recurring,
            NextExecutionEpoch = nextExecutionEpoch,
            };

            DoSchedule(scheduledAction);

            return scheduledAction;
        }