Пример #1
0
 private void InitTimer()
 {
     lock (_timerLock)
     {
         if (_started && _timer == null && _key != null)
         {
             _timer = ThreadPoolTimer.CreatePeriodicTimer((ThreadPoolTimer timer) =>
             {
                 FetchNews();
             }, TimeSpan.FromMinutes(5));
             FetchNews();
         }
     }
 }
Пример #2
0
        public MainPage()
        {
            this.InitializeComponent();
            ThreadPoolTimer timer = ThreadPoolTimer.CreatePeriodicTimer((t) =>
            {
                httpget();
            }, TimeSpan.FromMinutes(0.1));
            ThreadPoolTimer timer1 = ThreadPoolTimer.CreatePeriodicTimer((t) =>
            {
                initUltrasonic();
            }, TimeSpan.FromMinutes(0.1));

            InitGPIO();
        }
Пример #3
0
        private async Task StartVideoPreviewAsync()
        {
            await _mediaCapture.InitializeAsync();

            _displayRequest.RequestActive();

            PreviewControl.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();

            var timerInterval = TimeSpan.FromMilliseconds(66); //15fps

            ThreadPoolTimer.CreatePeriodicTimer(ProcessCurrentVideoFrame, timerInterval);
            _videoProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
        }
Пример #4
0
        private void ReStart()
        {
            this.btn_Refresh.IsEnabled = false;
            this._snowCount            = 0;
            this.listSnow.Clear();
            this.elapseSecond      = 0;
            this._snowHeight       = 0;
            this.pb_Progress.Value = 0;
            this.year = 2000;

            this.timerToShowProgress = ThreadPoolTimer.CreatePeriodicTimer(TimeToShowProgress, TimeSpan.FromSeconds(1));
            this.timerToCreateSnow   = ThreadPoolTimer.CreatePeriodicTimer(TimeToAddSnow, TimeSpan.FromMilliseconds(100));
            this.timerToMoveSnow     = ThreadPoolTimer.CreatePeriodicTimer(TimeToMoveSnow, TimeSpan.FromMilliseconds(50));
        }
 /// <summary>
 /// 循环定时器
 /// </summary>
 private void PeriodicTimer()
 {
     //循环定时器
     ThreadPoolTimer tptimer = ThreadPoolTimer.CreatePeriodicTimer(
         async(timer) =>
     {
         await Dispatcher.RunAsync(
             CoreDispatcherPriority.High, () =>
         {
             this.probar1.Value = this.probar1.Value + 1;
         });
     },
         TimeSpan.FromMilliseconds(100));
 }
Пример #6
0
        public async void UpdatingPinsThreadAndGui(TextBox[] NamesToUpdate, ToggleButton[] TogglesToUpdate, TextBlock Status, int TimerInSeconds)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("OutputNames.xml");


            Status.Text = "Connecting to FTP...";
            ConnectingToFtp();


            period = TimeSpan.FromSeconds(TimerInSeconds);


            ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source) =>
            {
                await ftp.ConnectAsync();
                isFileAvailable = await ftp.GetFileAsync("OutputNames.xml", file.Path);
                await ftp.DisconnectAsync();



                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High,
                                                                                                            async() =>
                {
                    try
                    {
                        NamesXML      = XDocument.Load(await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("OutputNames.xml"));
                        Status.Text   = "Reading New Settings";
                        var DataQuery = from r in NamesXML.Descendants("Output")
                                        select r;

                        Status.Text = "Flipping some buttons now :)";
                        TimeSpan.FromSeconds(1);
                        for (int i = 0; i < NamesToUpdate.Length; i++)
                        {
                            XElement Data         = DataQuery.ElementAt(i);
                            NamesToUpdate[i].Text = Data.Element("name").Value;

                            SetPinNumber(Convert.ToByte(i + 1));
                            ChangeState();
                        }
                        Status.Text = "Controls are Up-to-date";
                    }
                    catch (Exception e)
                    {
                    }
                }
                                                                                                            );
            }, period);
        }
Пример #7
0
        public async void UpdatingPinsThread(int TimerInSeconds)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("OutputNames.xml");

            ConnectingToFtp();


            period = TimeSpan.FromSeconds(TimerInSeconds);


            ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source) =>
            {
                await ftp.ConnectAsync();
                isFileAvailable = await ftp.GetFileAsync("OutputNames.xml", file.Path);
                await ftp.DisconnectAsync();



                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High,
                                                                                                            async() =>
                {
                    try
                    {
                        NamesXML = XDocument.Load(await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("OutputNames.xml"));

                        var DataQuery = from r in NamesXML.Descendants("Output")
                                        select r;

                        TimeSpan.FromSeconds(1);
                        for (int i = 0; i < 4; i++)
                        {
                            XElement Data = DataQuery.ElementAt(i);


                            if (OriginalStates[i] != Data.Element("status").Value)
                            {
                                OriginalStates[i] = Data.Element("status").Value;
                                SetPinNumber(Convert.ToByte(i + 1));
                                ChangeState();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
                                                                                                            );
            }, period);
        }
Пример #8
0
        public void StartTH()
        {
            Debug.WriteLine("StartTH()");

            bool RunTimmer = true;

            TimeSpan period = TimeSpan.FromMilliseconds(200);

            PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source) =>
            {
                //if (ConnectionService.isBackground) return;
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    try
                    {
                        if (RunTimmer)
                        {
                            RunTimmer = false;

                            if (PlugDeviceListSources.Count == 0 || PlugDeviceListSources.Count < ZigbeeDeviceService.ZigbeeDeviceListSources.Count)
                            {
                                PlugDeviceListSources = ZigbeeDeviceService.ZigbeeDeviceListSources;
                            }
                            else
                            {
                                if (ZigbeeDeviceService.ZigbeeDeviceListSources.Count > 0)
                                {
                                    for (int i = 0; i < PlugDeviceListSources.Count; i++)
                                    {
                                        if (JsonConvert.SerializeObject(PlugDeviceListSources[i]) != JsonConvert.SerializeObject(ZigbeeDeviceService.ZigbeeDeviceListSources[i]))
                                        {
                                            PlugDeviceListSources[i] = ZigbeeDeviceService.ZigbeeDeviceListSources[i];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("STartTH Exception : " + e.Message);
                    }
                    finally
                    {
                        RunTimmer = true;
                    }
                });
            }, period);
        }
Пример #9
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to start one or more asynchronous methods
            //

            // Keep this task running after this method has returned
            _deferral = taskInstance.GetDeferral();

            // Initial log
            LogTemperatures(null);

            // Then log every 5 minutes
            _timer = ThreadPoolTimer.CreatePeriodicTimer(LogTemperatures, TimeSpan.FromMinutes(5));
        }
Пример #10
0
        // websocket client events - open, messages, errors, closing
        private void mws_OpenEvent()
        {
            this.socketHeartBeatTimer = ThreadPoolTimer.CreatePeriodicTimer(OnHeartBeatTimerCallback, HandShake.HeartbeatInterval);
            this.ConnectionOpenEvent.Set();

            this.OnMessageEvent(new EventMessage()
            {
                Event = "open"
            });
            if (this.Opened != null)
            {
                try { this.Opened(this, EventArgs.Empty); }
                catch (Exception ex) { Debug.WriteLine(ex); }
            }
        }
Пример #11
0
 protected override void OnSubscribe(bool subscribe)
 {
     if (subscribe)
     {
         _timer ??= ThreadPoolTimer.CreatePeriodicTimer(PrepareNextFrame, _interval);
     }
     else
     {
         if (_timer != null)
         {
             _timer.Cancel();
             _timer = null;
         }
     }
 }
Пример #12
0
        public async Task Start()
        {
            this.IsLoading = true;
            await this.LoadImages();

            this.IsLoading = false;

            await this.ShowPhoto();

            ThreadPoolTimer.CreatePeriodicTimer(
                async(source) =>
            {
                await this.dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await this.ShowPhoto(); });
            }, TimeSpan.FromSeconds(10));
        }
Пример #13
0
        public void UpdateSlideshowImage(bool displayPrevious)
        {
            if (displayPrevious)
            {
                DisplayPreviousPicture();
            }
            else
            {
                DisplayNextPicture();
            }

            // Reset slideshow timer
            _slideshowTimer?.Cancel();
            _slideshowTimer = ThreadPoolTimer.CreatePeriodicTimer(SlideshowTimer_Elapsed, _interval);
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
            var cost     = BackgroundWorkCost.CurrentBackgroundWorkCost;
            var settings = ApplicationData.Current.LocalSettings;

            settings.Values["BackgroundWorkCost"] = cost.ToString();

            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            _deferral      = taskInstance.GetDeferral();
            _taskInstance  = taskInstance;
            _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
            throw new NotImplementedException();
        }
Пример #15
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral              = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCancelled;

            _watcher = new SerialWatcher();
            _watcher.OnSerialDiscoveryFinished += OnSerialDeviceDiscoveryFinished;
            _watcher.OnSerialDeviceAdded       += OnSerialDeviceDiscovered;
            _watcher.OnSerialDeviceRemoved     += OnSerialDeviceRemoved;

            _timer      = ThreadPoolTimer.CreatePeriodicTimer(OnTimerExpired, TimeSpan.FromMilliseconds(30000));
            _controller = GpioController.GetDefault();

            ConfigureLoRa();
        }
Пример #16
0
 public void StartReading(int interval)
 {
     //_tempTimer = new Timer(tempTimerCallback, null, (int)TimeSpan.FromMilliseconds(intervall).TotalMilliseconds, Timeout.Infinite);
     if (_tempTimerRun)
     {
         return;
     }
     _tempTimerRun = true;
     SetConvToAuto();
     _tempTimer = ThreadPoolTimer.CreatePeriodicTimer((t) =>
     {
         DataReadyFarEvent?.Invoke(this, GetTempF());
         DataReadyCelEvent?.Invoke(this, GetTempC());
     }, TimeSpan.FromMilliseconds(interval));
 }
Пример #17
0
 public object StartTimer(EventHandler <object> tickHandler, TimeSpan tickSpan, bool uiThread)
 {
     if (uiThread)
     {
         DispatcherTimer dt = new DispatcherTimer();
         dt.Tick    += tickHandler;
         dt.Interval = tickSpan;
         dt.Start();
         return(dt);
     }
     else
     {
         return(ThreadPoolTimer.CreatePeriodicTimer((timer) => tickHandler(this, timer), tickSpan));
     }
 }
Пример #18
0
        //let thread calculate the reputation and the visitorscount
        private void startThread()
        {
            ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source) =>
            {
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                                                            () =>
                {
                    // Your UI update code goes here!

                    calculateReputation();
                    calculateVisitors();
                }
                                                                                                            );
            }, period);
        }
Пример #19
0
        /// <summary>
        ///  Called when the page is loaded.  Used to setup our pooling of the BTLE device list during enumeration
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Feedback.Items.Clear();

            TimeSpan period = TimeSpan.FromSeconds(1);

            ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source) =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.High,
                                          () =>
                {
                    Update();
                });
            }, period);
        }
            public Shift165N(int PLPin, int CPPin, int CEPin, int Q7Pin, int NumOfRegisters)
            {
                this.PinPL = new PinOut(PLPin);
                this.PinCP = new PinOut(CPPin);
                this.PinCE = new PinOut(CEPin);
                this.PinQ7 = new PinIn(Q7Pin);

                //calculate the number of bits that need to be set
                PinQT = NumOfRegisters * 8 - 1;

                this.currentstate = new BitArray(PinQT + 1);

                read();
                this.timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_tick, TimeSpan.FromMilliseconds(125));
            }
Пример #21
0
        public QueueManager(BatchingLogAgent LogAgent)
        {
            logAgent   = LogAgent;
            dataClient = logAgent.Configuration.BatchAgent;

            QueuePollingInterval = logAgent.Configuration.QueuePollingInterval;

            failedSendCount = 0;
            sendCount       = 0;
#if SILVERLIGHT
            pollingTimer = new Timer(pollingTimer_Tick, null, QueuePollingInterval, QueuePollingInterval);
#else
            pollingTimer = ThreadPoolTimer.CreatePeriodicTimer(pollingTimer_Tick, QueuePollingInterval);
#endif
        }
Пример #22
0
        public async void StartPreview()
        {
            captureElement.Source = mediaCapture;
            // Cache the media properties as we'll need them later.
            var deviceController = this.mediaCapture.VideoDeviceController;

            this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

            await mediaCapture.StartPreviewAsync();

            // Use a 66 millisecond interval for our timer, i.e. 15 frames per second
            TimeSpan timerInterval = TimeSpan.FromMilliseconds(66);

            this.frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval);
        }
Пример #23
0
        public static void Start(IBackgroundTaskInstance taskInstance)
        {
            // Use the taskInstance.Name and/or taskInstance.InstanceId to determine
            // what background activity to perform. In this sample, all of our
            // background activities are the same, so there is nothing to check.
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            //
            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            //
            _deferral     = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
        }
Пример #24
0
        public void StartPeriodicTimer()
        {
            TimeSpan period = TimeSpan.FromSeconds(2);

            PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(
                async(src) => {
                var success = await RefreshValues();
                if (!success)
                {
                    src.Cancel();
                }
            },
                period
                );
        }
        public void Initialize(ReactContext reactContext)
        {
            Debug.WriteLine($"C# Properties.Prop1: {reactContext.Handle.Properties.Get(ReactPropertyBagHelper.GetName(null, "Prop1"))}");
            Debug.WriteLine($"C# Properties.Prop2: {reactContext.Handle.Properties.Get(ReactPropertyBagHelper.GetName(null, "Prop2"))}");

            _timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler((timer) =>
            {
                TimedEvent?.Invoke(++_timerCount);
                if (_timerCount == 5)
                {
                    _timer?.Cancel();
                }
            }),
                                                         TimeSpan.FromMilliseconds(TimedEventIntervalMS));
        }
Пример #26
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private async Task startPreview()
        {
            Debug.WriteLine("Start Preview");

            //プレビュースタート
            await capture.StartPreviewAsync();

            isPreview = true;

            //顔検出用タイマーの開始
            if (timer == null)
            {
                timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(CurrentVideoFrame), TimeSpan.FromMilliseconds(66));
            }
        }
Пример #27
0
        private void LaunchPokeballButton_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
        {
            GameClient.CurrentSession.Logger.Debug("Manipulation Completed...");

            // Disable the pokeball so that we can't try and throw it again
            ViewModel.PokeballButtonEnabled = false;

            var EndingX = (float)PokeballTransform.TranslateX;
            var EndingY = (float)PokeballTransform.TranslateY;

            // Pull out of the history where our finger was ~300ms ago
            var start     = PastPositions.Peek();
            var startTime = start.Item2;
            var startPos  = start.Item1;

            // TODO: Use PastPositions to determine if this is a curve ball, and if it is
            // apply a force in the direction of the curve

            // Get some details that we will need to do math with
            var displacement   = new Vector2(EndingX - startPos.X, EndingY - startPos.Y);
            var distance       = displacement.Length();
            var throwDirection = Vector3.Normalize(new Vector3(displacement.X, displacement.Y, 100.0f));
            var timeDelta      = (DateTime.Now - startTime).Milliseconds;

            // Set our initial position and velocity in world space
            ThrowItemPosition = new Vector3(EndingX, EndingY, 0);
            ThrowItemVelocity = distance * 100.0f / timeDelta * throwDirection;
            // Cutoff to prevent wasting balls when you didn't actually throw them
            if (ThrowItemVelocity.LengthSquared() < 100)
            {
                PokeballTransform.TranslateX    = InitItemX;
                PokeballTransform.TranslateY    = InitItemY;
                PokeballTransform.ScaleX        = 1;
                PokeballTransform.ScaleY        = 1;
                ViewModel.PokeballButtonEnabled = true;
                return;
            }

            /*
             * Logger.Write("Init throwDirection " + throwDirection.X + ", " + throwDirection.X + ", " + throwDirection.Z);
             * Logger.Write("Init TimeDelta " + timeDelta);
             * Logger.Write("Init Position " + ThrowItemPosition.X + ", " + ThrowItemPosition.Y + ", " + ThrowItemPosition.Z);
             * Logger.Write("Init Velocity " + ThrowItemVelocity.X + ", " + ThrowItemVelocity.Y + ", " + ThrowItemVelocity.Z);
             */

            prevTime = DateTime.Now;
            ThreadPoolTimer.CreatePeriodicTimer(PokeballUpdateLoop, TimeSpan.FromMilliseconds(20));
        }
Пример #28
0
        public async void InitSubscription()
        {
            ReaderMutex.WaitOne(MutexWaitTime); // Wait one minute for mutex
            // Query topic.
            try
            {
                byte[] queryTopicResponse = await HttpHelper.GetEntity(this.topicAddress);

                if (queryTopicResponse == null)
                {
                    return;
                }

                this.LogEvent(EventTypeConsts.Info, "Topic exists", this.topicAddress);


                // Query subscription.
                while (checkSubscription() == null)
                {
                    this.LogEvent(EventTypeConsts.Error, "Error reading subscription", this.subscriptionAddress);
                    await Task.Delay(TimeSpan.FromSeconds(60));
                }

                // Create a timer-initiated ThreadPool task to renew SAS token regularly
                SASTokenRenewTimer = ThreadPoolTimer.CreatePeriodicTimer(RenewSASToken, TimeSpan.FromMinutes(15));

                var dispatcher = DispatcherHelper.GetDispatcher;
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Task.Delay(TimeSpan.FromSeconds(5));
                    if (OnServiceBusConnected != null)
                    {
                        OnServiceBusConnected.Invoke(this.subscriptionAddress, this.subscriptionAddress);
                        this.LogEvent(EventTypeConsts.Info, "Binding done", "Servicebus handler listining for messages.");
                    }
                    else
                    {
                        this.LogEvent(EventTypeConsts.Error, "Error", "OnServiceBusConnected handlers not set");
                    }
                });
            }
            finally
            {
                ReaderMutex.ReleaseMutex();
                // Log view mode to collect data for Kiosks
                this.LogEvent(EventTypeConsts.Info, "View mode", String.Format("View IsMain: {0}, view count: {1} ", CoreApplication.GetCurrentView().IsMain, CoreApplication.Views.Count));
            }
        }
Пример #29
0
        private void runPauseButton_Click(object sender, RoutedEventArgs e)
        {
            SetRunPauseButton(simRunning);

            if (simRunning)
            {
                // Pause button clicked
                timer.Cancel();
            }
            else
            {
                // Run button clicked
                timer = ThreadPoolTimer.CreatePeriodicTimer(RunSimTick, new TimeSpan(0, 0, 0, 0, 1000 / (int)ticksPerSecond));
            }
            simRunning = !simRunning;
        }
Пример #30
0
        public async void Regist()
        {
            scheduled = true;
            OnPropertyChanged("scheduled");
            TimeSpan period = TimeSpan.FromSeconds(20);

            PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
            {
                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                    CoreDispatcherPriority.High,
                    () =>
                {
                    Click();
                });
            }, period);
        }