Change() public method

public Change ( System dueTime, System period ) : bool
dueTime System
period System
return bool
コード例 #1
1
        public MFTestResults TimerTest0()
        {
            MFTestResults result = MFTestResults.Pass;
            try
            {
                timerEvent.Reset();
                /// Save the current time shifted by 5 hours.
                
                timerTime = DateTime.UtcNow - utcTimeShiftAmount;
                using (Timer t = new Timer(new TimerCallback(TimerCallback), null, new TimeSpan(0, 0, 30), new TimeSpan(-TimeSpan.TicksPerMillisecond)))
                {
                    /// We shift the utc back by 5 hours.
                    TimeService.SetUtcTime(timerTime.Ticks); 
                    
                    /// timer should still fire after 30 seconds even though absolute time has been manipulated.
                    if (!timerEvent.WaitOne(2 * 60 * 1000, false))
                    {
                        result = MFTestResults.Fail;
                    }

                    /// Reset the changes.
                    TimeService.SetUtcTime((DateTime.UtcNow + utcTimeShiftAmount).Ticks);

                    t.Change(-1, -1);
                }
            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected exception", ex);
                result = MFTestResults.Fail;
            }

            return result;
        }
コード例 #2
0
        public BackupSetViewModel(IBackupSet backupSet, IUIVisualizerService uiVisualizerService)
        {
            Argument.IsNotNull(() => backupSet);
            Argument.IsNotNull(() => uiVisualizerService);
            BackupSet = backupSet;
            _uiVisualizerService = uiVisualizerService;
            _timer = new Timer(new TimerCallback((o)=>
            {
                RefreshLog();
            }), null, Timeout.Infinite, Timeout.Infinite);

            UpdateScheduleStatus();            
         
            BrowseSourceCommand = new Command(() => SourceDirectory = SetDirectory(SourceDirectory, "Select Source Directory"));
            BrowseDestinationCommand = new Command(() => DestinationDirectory = SetDirectory(DestinationDirectory, "Select Destination Directory"));
            ExcludeDirectoriesCommand = new Command(OnExcludeDirectoriesExecute, ()=>!String.IsNullOrEmpty(SourceDirectory));
            RunBackupCommand = new Command(() => 
                {
                    if(BackupSet.DestinationType == BackupDestinationType.ExternalDrive)
                    {
                        var typeFactory = this.GetTypeFactory();
                        var driveSelectionViewModel = typeFactory.CreateInstanceWithParametersAndAutoCompletion<DriveSelectionViewModel>();
                        driveSelectionViewModel.SetDefaultDrive(DestinationDirectory.Substring(0, 1));
                        if(_uiVisualizerService.ShowDialog(driveSelectionViewModel) == true )
                        {
                            UpdateDestinationDriveLetter(driveSelectionViewModel.SelectedDrive.Name);
                        }
                        else
                        {
                            return;
                        }
                        
                    }
                    _timer.Change(1000, 1000);
                    BackupSet.RunBackup();
                }  
                , () => CanRunBackup);

            CancelBackupCommand = new Command(() =>
                {
                    _timer.Change(Timeout.Infinite, Timeout.Infinite);
                    BackupSet.CancelBackup();
                }
                , () => CanCancelBackup);

            EditBackupSetCommand = new RelayCommand((o)=>
            {
                StateService.RequestBackupSetEdit((string)o);
            }
            ,(o) =>   ProcessingStatus == BackupProcessingStatus.NotStarted ||
                ProcessingStatus == BackupProcessingStatus.Cancelled ||
                ProcessingStatus == BackupProcessingStatus.Finished);

            FinishEditingBackupSetCommand = new RelayCommand((o) =>
            {
                StateService.RequestBackupSetEdit((string)o);
            });           
            
            BackupSet.PropertyChanged += BackupSetPropertyChanged;            
        }
コード例 #3
0
 public void Timer_Change_UInt32_Int64_AfterDispose_Throws()
 {
     var t = new Timer(EmptyTimerTarget);
     t.Dispose();
     Assert.Throws<ObjectDisposedException>(() => t.Change(0u, 0u));
     Assert.Throws<ObjectDisposedException>(() => t.Change(0L, 0L));
 }
コード例 #4
0
ファイル: Program.cs プロジェクト: matt-softlogic/samples
        public static void SendData(string serviceBusConnectionString, string entryHubName, string exitHubName)
        {
            var entryEventHub = EventHubClient.CreateFromConnectionString(serviceBusConnectionString, entryHubName);
            var exitEventHub = EventHubClient.CreateFromConnectionString(serviceBusConnectionString, exitHubName);
           
            var timerInterval = TimeSpan.FromSeconds(1);
            var generator = TollDataGenerator.Generator();

            TimerCallback timerCallback = state =>
            {
                var startTime = DateTime.UtcNow;
                generator.Next(startTime, timerInterval, 5);

                foreach (var e in generator.GetEvents(startTime))
                {
                    if (e is EntryEvent)
                    {
                        entryEventHub.Send(
                           new EventData(Encoding.UTF8.GetBytes(e.Format()))
                                    {
                                        PartitionKey = e.TollId.ToString(CultureInfo.InvariantCulture)
                                    });
                    }
                    else
                    {
                        exitEventHub.Send(
                           new EventData(Encoding.UTF8.GetBytes(e.Format()))
                           {
                               PartitionKey = e.TollId.ToString(CultureInfo.InvariantCulture)
                           });
                    }
                }

                timer.Change((int)timerInterval.TotalMilliseconds, Timeout.Infinite);
            };

            timer = new Timer(timerCallback, null, Timeout.Infinite, Timeout.Infinite);
            timer.Change(0, Timeout.Infinite);

            Console.WriteLine("Sending event hub data... Press Ctrl+c to stop.");

            var exitEvent = new ManualResetEvent(false);
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Stopping...");
                eventArgs.Cancel = true;
                exitEvent.Set();
            };

            exitEvent.WaitOne();
            Console.WriteLine("Shutting down all resources...");
            timer.Change(Timeout.Infinite, Timeout.Infinite);
            Thread.Sleep(timerInterval);
            timer.Dispose();
            entryEventHub.Close();
            exitEventHub.Close();
            Console.WriteLine("Stopped.");
        }
コード例 #5
0
ファイル: PaBalls2016CS20Alpha.cs プロジェクト: asm32cn/CS
 public void PA_DoSwitchTimer()
 {
     if (isRunning)
     {
         timer.Change(System.Threading.Timeout.Infinite, nTimerInterval);
     }
     else
     {
         timer.Change(0, nTimerInterval);
     }
     isRunning = !isRunning;
 }
コード例 #6
0
ファイル: Program.cs プロジェクト: IanYates/EasyNetQ
        static void Main(string[] args)
        {
            var bus = RabbitHutch.CreateBus("host=localhost");
            var count = 0;

            var timer = new Timer(x =>
            {
                try
                {
                    using (var publishChannel = bus.OpenPublishChannel())
                    {
                        publishChannel.Request<TestRequestMessage, TestResponseMessage>(
                            new TestRequestMessage { Text = string.Format("Hello from client number: {0}! ", count++) },
                            ResponseHandler);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception thrown by Publish: {0}", exception.Message);
                }
            }, null, 1000, 1000);

            Console.Out.WriteLine("Timer running, ctrl-C to end");

            Console.CancelKeyPress += (source, cancelKeyPressArgs) =>
            {
                Console.Out.WriteLine("Shutting down");

                timer.Dispose();
                bus.Dispose();
                Console.WriteLine("Shut down complete");
            };

            var running = true;
            while (true)
            {
                Console.ReadKey();
                if (running)
                {
                    timer.Change(Timeout.Infinite, Timeout.Infinite);
                }
                else
                {
                    timer.Change(1000, 1000);
                }
                running = !running;
            }
        }
コード例 #7
0
        /// <summary>
        /// Handle the scenario when PersistTo == 1
        /// </summary>
        public IObserveOperationResult HandleMasterPersistence(ICouchbaseServerPool pool)
        {
            try
            {
                var commandConfig = setupObserveOperation(pool);
                var node = commandConfig.Item2[0] as CouchbaseNode;
                IObserveOperationResult result = new ObserveOperationResult();

                do
                {
                    var are = new AutoResetEvent(false);
                    var timer = new Timer(state =>
                    {
                        result = node.ExecuteObserveOperation(commandConfig.Item3);

                        if (log.IsDebugEnabled) log.Debug("Node: " + node.EndPoint + ", Result: " + result.KeyState + ", Cas: " + result.Cas + ", Key: " + _settings.Key);

                        if (result.Success && result.Cas != _settings.Cas && result.Cas > 0)
                        {
                            result.Fail(ObserveOperationConstants.MESSAGE_MODIFIED);
                            are.Set();
                        }
                        else if (result.KeyState == ObserveKeyState.FoundPersisted)
                        {
                            result.Pass();
                            are.Set();
                        }

                    }, are, 0, 500);

                    if (!are.WaitOne(_settings.Timeout))
                    {
                        timer.Change(-1, -1);
                        result.Fail(ObserveOperationConstants.MESSAGE_TIMEOUT, new TimeoutException());
                        break;
                    }

                    timer.Change(-1, -1);

                } while (result.Message == string.Empty && result.KeyState != ObserveKeyState.FoundPersisted);

                return result;
            }
            catch (Exception ex)
            {
                return new ObserveOperationResult { Success = false, Exception = ex };
            }
        }
コード例 #8
0
ファイル: Uvss.cs プロジェクト: Cyuliang/CheckShow
        /// <summary>
        /// 链接车底系统
        /// </summary>
        /// <param name="state"></param>
        private void AutoLinkCallBack(object state)
        {
            try
            {
                int ret = SafeNativeMethods.UVSSConnect(UVSSIp, UVSSPort);
                if (ret > 0)
                {
                    _TimerLink?.Change(-1, -1);

                    ip     = IPAddress.Parse(UVSSIp);
                    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    client.Connect(new IPEndPoint(ip, UVSSPort));//链接测试socket

                    _TimerTestLink?.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(0));
                    LinkStatusAction?.Invoke(true);

                    Lognet.Log.Warn("车底系统链接成功");
                }
                else
                {
                    SafeNativeMethods.UVSSDisconnect(ret);
                    _TimerLink?.Change(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
                    //_TimerTestLink.Change(-1, -1);
                    //LinkStatusAction?.Invoke(false);
                }
            }
            catch (Exception)
            {
                GC.Collect();
            }
        }
コード例 #9
0
ファイル: WlanClient.cs プロジェクト: jcookems/freezing-ninja
        private async Task<IEnumerable<WlanInterop.WlanBssEntry>> GetNetworkBssList(Guid interfaceGuid)
        {
            WlanInterop.WlanScan(this.clientHandle, interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            // Ideally, wait for a callback, but there were some COM timing issues with that.
            // So just wait.
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            Timer timer = null;
            timer = new Timer(s =>
            {
                timer.Dispose();
                tcs.SetResult(true);
            }, null, -1, -1);
            timer.Change(5000, -1);
            await tcs.Task;

            IntPtr wlanBssList = IntPtr.Zero;
            List<WlanInterop.WlanBssEntry> result;
            try
            {
                WlanInterop.WlanGetNetworkBssList(this.clientHandle, interfaceGuid, IntPtr.Zero, WlanInterop.Dot11BssType.Any, false, IntPtr.Zero, out wlanBssList);
                result = this.GetBssListFromPointer(wlanBssList);
            }
            finally
            {
                WlanInterop.WlanFreeMemory(wlanBssList);
            }
            return result;
        }
コード例 #10
0
    static void Main()
        {
            // Create an event to signal the timeout count threshold in the 
            // timer callback.
            AutoResetEvent autoEvent     = new AutoResetEvent(false);

            StatusChecker  statusChecker = new StatusChecker(10);

            // Create an inferred delegate that invokes methods for the timer.
            TimerCallback tcb = statusChecker.CheckStatus;

            // Create a timer that signals the delegate to invoke  
            // CheckStatus after one second, and every 1/4 second  
            // thereafter.
            Console.WriteLine("{0} Creating timer.\n", 
                              DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);

            // When autoEvent signals, change the period to every 
            // 1/2 second.
            autoEvent.WaitOne(5000, false);
            stateTimer.Change(0, 500);
            Console.WriteLine("\nChanging period.\n");

            // When autoEvent signals the second time, dispose of  
            // the timer.
            autoEvent.WaitOne(5000, false);
            stateTimer.Dispose();
            Console.WriteLine("\nDestroying timer.");
        }
コード例 #11
0
        public DynamicRangeChunkVolume(GraphicsDevice device, GameDataProvider provider)
        {
            chunkWishList = new HashSet<WorldPosition>();
            this.provider = provider;
            volume = new Chunk[16, 16, 16];
            vertexBuffers = new CDictionary<Chunk, VBuffer7>();
            this.device = device;
            this.effect = Static.Effect;
            MiniMap = new Texture2D(Static.Device, 64, 64);
            MiniMapBuffer = new Color[64 * 64];
            MiniMapLayer = new Layer(MiniMap, 1, 0.7f, LayerDock.Far, LayerDock.Far,
                () =>
                {
                    return true;
                }
                );
            MiniMapLayer.Push(new LayerCell
            {
                SourceTexture = new Rectangle(0, 0, 64, 64),
                DestinationScreen = new Rectangle(-270, -270, 256, 256)
            });

            redrawWorker = new Timer(doRedraw);
            redrawWorker.Change(50, 50);

            hoverBoxMesh = HelpfulStuff.getCube(0.51f, GraphicsHelper.TextureCoord(36));
        }
コード例 #12
0
ファイル: Processor.cs プロジェクト: hbre/AdalightNet
 public void Run(ILedService ledService)
 {
     _ledService = ledService;
     _timer = new Timer(Tick);
     GC.KeepAlive(_timer);
     _timer.Change(200, LedConstants.TICK_EVERY_MILISEC);
 }
コード例 #13
0
ファイル: MainVM.cs プロジェクト: Jitlee/RemoteShutdown
        private MainVM()
        {
            #if DEBUG
            LoggerFactory.SetLoggerLevel(LoggerLevel.Trance);
            #else
            LoggerFactory.SetLoggerInstance(typeof(MyLogger));
            #endif

            _udpClient = new UdpClient();
            _udpClient.RequestAction = ServerRequest;

            _autoTimer = new Timer(AtuoTimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            _tcpClient = new TcpClient();
            _tcpClient.OpenedAction = ServerOpened;
            _tcpClient.ClosedAction = ServerClosed;
            _tcpClient.FaultAction = ServerFaulted;
            _tcpClient.ReceivedAction = Received;

            if (SettingVM.Instance.AutoAddress)
            {
                _udpClient.Start();
            }
            else
            {
                _autoTimer.Change(Common.AutoConnectInterval, Common.AutoConnectInterval);
            }
        }
コード例 #14
0
ファイル: TimerChangeTests.cs プロジェクト: jmhardison/corefx
 public void Timer_Change_TooLongTimeSpan_Period_Throws()
 {
     using (var t = new Timer(new TimerCallback(EmptyTimerTarget), null, 1, 1))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => t.Change(new TimeSpan(1) /* not relevant */, TimeSpan.FromMilliseconds((long)0xFFFFFFFF)));
     }
 }
コード例 #15
0
ファイル: TimerChangeTests.cs プロジェクト: jmhardison/corefx
 public void Timer_Change_NegativeInt_Period_Throws()
 {
     using (var t = new Timer(new TimerCallback(EmptyTimerTarget), null, 1, 1))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => t.Change(1 /* not relevant */, -2));
     }
 }
コード例 #16
0
        public int ScheduleTask(Action action, int dueTime, int period)
        {
            var taskId = Interlocked.Increment(ref _taskCount);
            var timer = new Timer((obj) =>
            {
                var state = (TimerState)obj;
                Timer currentTimer;
                if (_timerDict.TryGetValue(state.TaskId, out currentTimer))
                {
                    currentTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    try
                    {
                        action();
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Schedule task has exception.", ex);
                    }
                    finally
                    {
                        currentTimer.Change(state.Period, state.Period);
                    }
                }
            }, new TimerState(taskId, dueTime, period), Timeout.Infinite, Timeout.Infinite);

            _timerDict.Add(taskId, timer);

            timer.Change(dueTime, period);

            return taskId;
        }
コード例 #17
0
        protected override void OnStartup()
        {
            m_Timer = new Timer(TimerCallback);
            m_Timer.Change(100, 100);

            base.OnStartup();
        }
コード例 #18
0
 public ProductivityManager()
 {
     _load();
     AppSettings = new Settings();
     _timer = new Timer(_timerCallback);
     _timer.Change(1000, 1000);
 }
コード例 #19
0
ファイル: ViewViewModel.cs プロジェクト: yeenfei/samples
        public ViewViewModel()
        {
            chatService = ServiceLocator.Current.GetInstance<IChatService>();
            parentViewModel = ServiceLocator.Current.GetInstance<PhotosViewModel>();
            timer = new Timer(new TimerCallback((c) => {
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    App.RootFrame.Navigate(new Uri("/View/PhotosPage.xaml", UriKind.RelativeOrAbsolute));
                });
            }),
            null,
            Timeout.Infinite,
            Timeout.Infinite);

            HideCommand = new RelayCommand(async () =>

            {
                timer.Change(TimeSpan.FromSeconds(6), TimeSpan.FromMilliseconds(-1));
                var contentList = await chatService.ReadPhotoContentAsync(
                    parentViewModel.SelectedPhoto.PhotoContentSecretId);
                var content = contentList.FirstOrDefault();
                if (content != null)
                {
                    Uri = chatService.ReadPhotoAsUri(content.Uri);
                    Stream = chatService.ReadPhotoAsStream(content.Uri);
                }
                else
                {
                    Uri = null;
                    Stream = null;
                }

            });
        }
コード例 #20
0
ファイル: Orquestrator.cs プロジェクト: RepoCorp/Prodactive
        private Orquestrator()
        {
            Timer t= new Timer(new TimerCallback(VerificarRetos));
            t.Change(60*60*1000, 0);//Cada Hora

            Task.Factory.StartNew(() => VerificarRetos(new object()));
        }
コード例 #21
0
        public MainForm()
        {
            InitializeComponent();

            // member initialization
            m_searchControls = new List<SearchClauseControl>();

            // update the title with the version
            this.Text += " " + AboutForm.GetVersionString(false);

            // create the timer and start it
            m_timerCacheStatus = new System.Threading.Timer(TimerCacheStatusCallback);
            m_timerCacheStatus.Change(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));

            // attach event handlers
            this.Load += new EventHandler(MainForm_Load);
            this.Shown += new EventHandler(MainForm_Shown);
            this.KeyDown += new KeyEventHandler(MainForm_KeyDown);
            this.FormClosed += new FormClosedEventHandler(MainForm_FormClosed);
            menu_file_import.Click += new EventHandler(menu_file_import_Click);
            menu_file_export.Click += new EventHandler(menu_file_export_Click);
            menu_file_exit.Click += new EventHandler(menu_file_exit_Click);
            menu_reports_category.Click += new EventHandler(menu_reports_category_Click);
            menu_reports_location.Click += new EventHandler(menu_reports_location_Click);
            menu_reports_loadouts.Click += new EventHandler(menu_reports_loadouts_Click);
            menu_reports_material.Click += new EventHandler(menu_reports_material_Click);
            menu_reports_pos.Click += new EventHandler(menu_reports_pos_Click);
            menu_options_refresh.Click += new EventHandler(menu_options_refresh_Click);
            menu_options_keys.Click += new EventHandler(menu_options_keys_Click);
            menu_options_options.Click += new EventHandler(menu_options_options_Click);
            menu_help_about.Click += new EventHandler(menu_help_about_Click);
        }
コード例 #22
0
ファイル: ServerObject.cs プロジェクト: Tankerxyz/localTanks
        // прослушивание входящих подключений
        public void Listen() {
            
            Thread handlerThread = new Thread( new ThreadStart(Handler) );
            handlerThread.Start();

            Timer timerChecker = new Timer(new TimerCallback(chekerConnections));
            timerChecker.Change(1000, 1000);

            Console.WriteLine("Сервер запущен. Ожидание подключений...");
            updateTitle();

            IPEndPoint remoteIp = null;
            try {
                while (true) {

                    byte[] data = receiver.Receive(ref remoteIp);
                    packages.Enqueue(new Package(Encoding.Unicode.GetString(data), new IPEndPoint(remoteIp.Address, remoteIp.Port)));
                    
                }

            } catch (Exception ex) {

                Console.WriteLine(ex.Message);
                Environment.Exit(0);

            }
        }
コード例 #23
0
        public void ScheduleService()
        {
            try
            {
                Schedular = new Timer(SchedularCallback);
                var mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
                LogIt.WriteToFile("{0}" + "Mode - " + mode);

                //Set the Default Time.
                DateTime scheduledTime = DateTime.MinValue;

                if (mode == "DAILY")
                {
                    //Get the Scheduled Time from AppSettings.
                    scheduledTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]);
                    if (DateTime.Now > scheduledTime)
                    {
                        //If Scheduled Time is passed set Schedule for the next day.
                        scheduledTime = scheduledTime.AddDays(1);
                    }
                }

                if (mode.ToUpper() == "INTERVAL")
                {
                    //Get the Interval in Minutes from AppSettings.
                    int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);

                    //Set the Scheduled Time by adding the Interval to Current Time.
                    scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
                    if (DateTime.Now > scheduledTime)
                    {
                        //If Scheduled Time is passed set Schedule for the next Interval.
                        scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
                    }
                }

                TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
                var schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);

                LogIt.WriteToFile("{0}" + "Next Run In - " + schedule);
                //LogIt.WriteToFile("Simple Service scheduled to run in: " + schedule + " {0}");

                //Get the difference in Minutes between the Scheduled and Current Time.
                var dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);

                //Change the Timer's Due Time.
                Schedular.Change(dueTime, Timeout.Infinite);
            }
            catch (Exception ex)
            {
                //LogIt.WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
                LogIt.WriteToFile("{0}" + "Error - " + ex.Message + ex.StackTrace);

                //Stop the Windows Service.
                using (var serviceController = new ServiceController(Config.ServiceName))
                {
                    serviceController.Stop();
                }
            }
        }
コード例 #24
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var cts = new CancellationTokenSource();
            var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
            var linkedToken = linkedTokenSource.Token;
            var timer = new Timer(s_timerCallback, cts, -1, -1);

            request.RegisterForDispose(timer);
            request.RegisterForDispose(cts);
            request.RegisterForDispose(linkedTokenSource);

            timer.Change(_milliseconds, -1);

            return base.SendAsync(request, linkedToken).ContinueWith(task => {

                if (task.Status == TaskStatus.Canceled) {

                    return request.CreateResponse(HttpStatusCode.RequestTimeout);
                }

                //TODO: Handle faulted task as well

                return task.Result;

            }, TaskContinuationOptions.ExecuteSynchronously);
        }
コード例 #25
0
        public ExecutionPipeline(Kernel kernel)
        {
            _kernel = kernel;
            _commandQueue = new BufferBlock<CommandRequest[]>();
            _queryQueue = new BatchBlock<QueryRequest>(MaxConcurrentQueries);

            var transactionHandler = new ActionBlock<object>(t =>
            {
                if (t is QueryRequest[])
                {
                    var queries = t as QueryRequest[];
                    Task[] tasks = queries.Select(q => Task.Factory.StartNew(_ => ExecuteQuery(q), null)).ToArray();
                    Task.WaitAll(tasks);
                }
                else if (t is CommandRequest[])
                {
                    var commands = t as CommandRequest[];
                    foreach (var commandContext in commands)
                    {
                        var result = _kernel.Execute(commandContext.Command);
                        commandContext.Response.Post(result);
                    }
                }

            });
            _commandQueue.LinkTo(transactionHandler);
            _queryQueue.LinkTo(transactionHandler);
            _timer = new Timer(_ => _queryQueue.TriggerBatch());
            _timer.Change(Interval, Interval);
        }
コード例 #26
0
ファイル: TimerHelper.cs プロジェクト: Dev01FC/CnC-SC
        public void Start(TimeSpan timerInterval, bool triggerAtStart = false,
            object state = null)
        {
            Stop();
            _timer = new System.Threading.Timer(Timer_Elapsed, state,
                System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);

            if (triggerAtStart)
            {
                _timer.Change(TimeSpan.FromTicks(0), timerInterval);
            }
            else
            {
                _timer.Change(timerInterval, timerInterval);
            }
        }
コード例 #27
0
        void WalkTimerElapsed(object sender)
        {
            double distance = Vector3d.Distance(Client.Self.GlobalPosition, walkToTarget);

            if (distance < 2d)
            {
                // We're there
                EndWalking();
            }
            else
            {
                if (lastDistance != (int)distance)
                {
                    lastDistanceChanged = Environment.TickCount;
                    lastDistance        = (int)distance;
                }
                else if ((Environment.TickCount - lastDistanceChanged) > 10000)
                {
                    // Our distance to the target has not changed in 10s, give up
                    EndWalking();
                    return;
                }
                walkTimer?.Change(walkChekInterval, Timeout.Infinite);
            }
        }
コード例 #28
0
ファイル: Plugin.cs プロジェクト: immeraufdemhund/SourceLog
        public virtual void Initialise()
        {
            SourceLogLogger.LogInformation("Plugin initialising","Plugin." + GetType().Name);

            Timer = new Timer(CheckForNewLogEntries);
            Timer.Change(0, 15000);
        }
コード例 #29
0
        public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken = default(CancellationToken)) {
            // Validate arguments
            if (factory == null)
                throw new ArgumentNullException(nameof(factory));
            if (millisecondsDelay < 0)
                throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));

            // Create the timed task
            var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
            var ctr = default(CancellationTokenRegistration);

            // Create the timer but don't start it yet.  If we start it now,
            // it might fire before ctr has been set to the right registration.
            var timer = new Timer(self => {
                // Clean up both the cancellation token and the timer, and try to transition to completed
                ctr.Dispose();
                (self as Timer)?.Dispose();
                tcs.TrySetResult(null);
            }, null, -1, -1);

            // Register with the cancellation token.
            if (cancellationToken.CanBeCanceled) {
                // When cancellation occurs, cancel the timer and try to transition to canceled.
                // There could be a race, but it's benign.
                ctr = cancellationToken.Register(() => {
                    timer.Dispose();
                    tcs.TrySetCanceled();
                });
            }

            // Start the timer and hand back the task...
            timer.Change(millisecondsDelay, Timeout.Infinite);
            return tcs.Task;
        }
コード例 #30
0
        public MainWindow()
        {
            InitializeComponent();

            if (File.Exists(ConfigurationFile))
            {
                try
                {
                    _configuration = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText(ConfigurationFile));
                }
                catch (Exception)
                {
                    Debug.WriteLine("Cannot load configuration file {0}", ConfigurationFile);
                }
            }

            if (_configuration == null)
            {
                _configuration = Configuration.Default;
                File.WriteAllText(ConfigurationFile, JsonConvert.SerializeObject(_configuration, new JsonSerializerSettings() { Formatting = Formatting.Indented }));
            }

            DataContext = this;

            _timer = new Timer(ShowBalloon);
            _timer.Change(TimeSpan.FromMinutes(_configuration.StartAfterMinutes),
                TimeSpan.FromHours(_configuration.AfterHours).Add(TimeSpan.FromMinutes(_configuration.AfterMinutes)));
        }
コード例 #31
0
ファイル: Time.cs プロジェクト: busterwood/NetChan
 public static Channel<DateTime> After(TimeSpan after)
 {
     var ch = new Channel<DateTime>(1);
     var t = new Timer(state => { ch.TrySend(DateTime.Now); ch.Close(); });
     t.Change(after, TimeSpan.FromMilliseconds(-1));
     return ch;
 }
コード例 #32
0
        public PythonInterpreterFactoryWithDatabase(
            Guid id,
            string description,
            InterpreterConfiguration config,
            bool watchLibraryForChanges
        ) {
            _description = description;
            _id = id;
            _config = config;

            if (watchLibraryForChanges && Directory.Exists(_config.LibraryPath)) {
                _refreshIsCurrentTrigger = new Timer(RefreshIsCurrentTimer_Elapsed);

                _libWatcher = CreateLibraryWatcher();

                _isCheckingDatabase = true;
                _refreshIsCurrentTrigger.Change(1000, Timeout.Infinite);

                _verWatcher = CreateDatabaseVerWatcher();
                _verDirWatcher = CreateDatabaseDirectoryWatcher();
            }

            // Assume the database is valid if the directory exists, then switch
            // to invalid after we've checked.
            _isValid = Directory.Exists(DatabasePath);
        }
コード例 #33
0
    void Start()
    {
        TextAsset    file   = (TextAsset)Resources.Load("output");
        StringReader reader = new StringReader(file.text);
        string       keylog = reader.ReadToEnd();

        reader.Close();

        keylog = new Regex("\n+").Replace(keylog, "\n");
        string[] weLines = keylog.Split('\n');

        int desiredSize = 100;
//		string[] newLines = new string[desiredSize];

        int startingPlace = (int)Random.Range(0, weLines.Length - desiredSize);

        for (int i = startingPlace; i < startingPlace + desiredSize; i++)
        {
//			newLines [i - startingPlace] = weLines [i];
            weString += weLines [i];
        }
//		lines = newLines;


        font = Font.CreateDynamicFontFromOSFont("Menlo", 45);

        textContents = "";
        timer        = new System.Threading.Timer(UpdateProperty);
        timer.Change(timerUpdatePeriod, timerUpdatePeriod);
    }
コード例 #34
0
ファイル: AuthQueue.cs プロジェクト: pallmall/WCell
		static AuthQueue()
		{
			s_queuedClients = new LockfreeQueue<IRealmClient>();
			s_checkTimer = new Timer(ProcessQueuedClients);

			s_checkTimer.Change(TimeSpan.FromSeconds(15.0), TimeSpan.FromSeconds(15.0));
		}
コード例 #35
0
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return(Task.CompletedTask);
        }
コード例 #36
0
ファイル: SystemRefresher.cs プロジェクト: nono3551/paco
        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("SystemRefresh is stopping.");

            _timer?.Change(Timeout.Infinite, 0);
            _timer?.Dispose();

            return(Task.CompletedTask);
        }
コード例 #37
0
 public void DisposeResources(GraphicsContext graphics)
 {
     _updateTimer?.Change(Timeout.Infinite, Timeout.Infinite);
     _updateTimer = null;
     _bitmap?.Dispose();
     _bitmap = null;
     _brush?.Dispose();
     _bitmapMemory = null;
 }
コード例 #38
0
        private void HidePopup()
        {
            if (this.Visible)
            {
                this.Visible = false;
            }

            _hideTimer?.Change(Timeout.Infinite, Timeout.Infinite);
        }
コード例 #39
0
ファイル: GPSReader.cs プロジェクト: alexbzg/tnxqso-client
 private void  stopListenWirelessGW()
 {
     if (listenWirelessGWFl)
     {
         listenWirelessGWFl = false;
         wirelessGWCheckTimer?.Change(Timeout.Infinite, Timeout.Infinite);
         gpsShare?.disconnect();
     }
 }
コード例 #40
0
        protected override void OnDisappearing()
        {
            base.OnDisappearing();

            _calcTimer?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
            _calcTimer?.Dispose();

            REnv.SaveValue();
        }
コード例 #41
0
 public void ChangeTimer(int interval)
 {
     if (playMode != 1)
     {
         return;
     }
     else
     {
         if (interval > 0)
         {
             playbackTimer.Change(0, interval);
         }
         else
         {
             playbackTimer.Change(-1, -1);
         }
     }
 }
コード例 #42
0
    void Start()
    {
        TextAsset    file   = (TextAsset)Resources.Load("output");
        StringReader reader = new StringReader(file.text);
        string       keylog = reader.ReadToEnd();

        reader.Close();

        keylog = new Regex("\n+").Replace(keylog, "\n");
        string[] weLines = keylog.Split('\n');

        int desiredSize = 1000;

        int startingPlace = (int)UnityEngine.Random.Range(0, weLines.Length - desiredSize);

        for (int i = startingPlace; i < startingPlace + desiredSize; i++)
        {
            weString += weLines [i];
        }

//		weString = "";
//		while (weString.Length < desiredSize) {
//			for (int i = 0; i < 3; i++) {
//				for (int j = 0; j < 7; j++) { weString += "j"; }
//				weString += "k";
//			}
//			for (int j = 0; j < 6; j++) {
//				weString += "j";
//			}
//			weString += "k ";
//		}


//		for (int i = 0; i < desiredSize; i++) {
//			weString += UnityEngine.Random.value < 0.5f ? "j" : "k";
//		}

        panel = Instantiate(panel, transform.position, panel.transform.rotation);
        panel.gameObject.transform.position = new Vector2(300f, 200f);

        panel.transform.SetParent(renderCanvas.transform);

        for (int i = 0; i < desiredSize; i++)
        {
            letters.Add((Text)Instantiate(letter, box.transform.position, transform.rotation));
            letters[i].text = weString [i] + "";
            letters[i].transform.SetParent(panel.transform, false);
        }


        timer = new System.Threading.Timer(UpdateProperty);
        timer.Change(timerUpdatePeriod, timerUpdatePeriod);
    }
コード例 #43
0
 /// <summary>
 /// Returns once the processing thread has been killed.
 /// </summary>
 public void Stop()
 {
     frameBufferTimer?.Change(Timeout.Infinite, Timeout.Infinite);
     frameBufferTimer = null;
     if (processorThread != null)
     {
         shouldStop = true;
         while (processorThread.IsAlive)
         {
             Thread.Sleep(500);
         }
     }
 }
コード例 #44
0
ファイル: Uvss.cs プロジェクト: Cyuliang/CheckShow
        //[DllImport("kernel32.dll")]
        //static extern uint GetTickCount();
        //static void Delay(int ms)
        //{
        //    uint start = GetTickCount();
        //    while (GetTickCount() - start < ms)
        //    {
        //        Application.DoEvents();
        //    }
        //}

        /// <summary>
        /// 循环测试链接状态
        /// </summary>
        /// <param name="state"></param>
        private void TestLinCallBack(object state)
        {
            while (true)
            {
                try
                {
                    client.Send(Encoding.ASCII.GetBytes(""));
                    _TimerLink?.Change(-1, -1);
                    LinkStatusAction?.Invoke(true);
                    Thread.Sleep(1000);
                }
                catch (Exception)
                {
                    Lognet.Log.Warn("车底系统端服务关闭");
                    client.Shutdown(SocketShutdown.Both);
                    client.Close();
                    _TimerLink?.Change(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
                    LinkStatusAction?.Invoke(false);
                    break;
                }
            }
        }
コード例 #45
0
ファイル: WebSocketHelper.cs プロジェクト: yuzd/AntDeploy
 private void Ping(object state)
 {
     try
     {
         if (_dispose)
         {
             return;
         }
         mDetectionTimer?.Change(-1, -1);
         try
         {
             SendText("ping").ConfigureAwait(false);
         }
         finally
         {
             mDetectionTimer?.Change(1000 * 2, 1000 * 2);
         }
     }
     catch (Exception)
     {
     }
 }
コード例 #46
0
 private void RestartTimer(int msDelay)
 {
     lock (_lockingObject)
     {
         if (timerDisposed.WaitOne(1))
         {
             return;
         }
         if (Interlocked.Read(ref _shouldTimerRun) == 1)
         {
             _timer?.Change(msDelay, Int32.MaxValue);
         }
     }
 }
コード例 #47
0
        protected internal void ProcessTrackInfo(Status newTrackInfo)
        {
            if (newTrackInfo == null)
            {
                return;
            }
            var newTrackInfoUri = newTrackInfo.track?.track_resource?.uri;

            if (CurrentTrackInfo?.track?.track_resource == null || CurrentTrackInfo.track.track_resource.uri
                != newTrackInfoUri)
            {
                CurrentTrackInfo = newTrackInfo;
                OnTrackChanged();
                _songStatusWatcher?.Change(
                    GetDelayForPlaybackUpdate(newTrackInfo.playing_position), 1000);
            }
            else
            {
                CurrentTrackInfo = newTrackInfo;
                OnTrackTimerChanged();
                _songStatusWatcher?.Change(
                    GetDelayForPlaybackUpdate(newTrackInfo.playing_position), 1000);
            }
        }
コード例 #48
0
 private void Tick(object state)
 {
     try
     {
         var api        = new ExternalApi();
         var updateList = api.FetchDataFromExternalApi().Result;
         if (updateList != null)
         {
             _companyRepository.MergeUpdateList(updateList).Wait();
         }
     }
     finally
     {
         _timer?.Change(Interval, Timeout.Infinite);
     }
 }
コード例 #49
0
 private void LoginTick(object state)
 {
     try
     {
         var key = Registry.CurrentUser.OpenSubKey("LoRTracker");
         if (key.GetValue("username") != null)
         {
             TryLogin((string)key.GetValue("username", null), (string)key.GetValue("password", null)).Wait();
             UpdatePollingRates();
         }
     }
     finally
     {
         _LoginTimer?.Change(_LoginInterval, Timeout.Infinite);
     }
 }
コード例 #50
0
ファイル: InvokeSelf.cs プロジェクト: gigavat/InvokeSelf
        private static Task Delay(Control control)
        {
            var tcs = new TaskCompletionSource <object>();

            _waitingMainFormTimer = new Timer(o =>
            {
                if (control.IsHandleCreated)
                {
                    tcs.TrySetResult(null);
                    _waitingMainFormTimer?.Change(Timeout.Infinite, Timeout.Infinite);
                    _waitingMainFormTimer = null;
                }
            });
            _waitingMainFormTimer.Change(0, 20);
            return(tcs.Task);
        }
コード例 #51
0
 private static void StartDispatching(Object state)
 {
     Settings.Log.Debug($"{nameof(StartDispatching)}");
     try
     {
         _Timer.Change(Timeout.Infinite, Timeout.Infinite);
         SendInformationToShare();
     }
     catch (Exception ex)
     {
         Settings.Log.Error(ex);
     }
     finally
     {
         _Timer?.Change(_CheckIntervalMs, Timeout.Infinite);
     }
 }
コード例 #52
0
        public void SurfaceCreated(ISurfaceHolder holder)
        {
            if (nativeWindow == IntPtr.Zero)
            {
                nativeWindow = ANativeWindow_fromSurface(JniEnvironment.EnvironmentPointer, Holder.Surface.Handle);
            }
            appPaused = false;

            //_gameTimer.Start();
            _tickTimer = new System.Threading.Timer(state =>
            {
                Application.SynchronizationContext.Send(_ => { if (!appPaused)
                                                               {
                                                                   Tick();
                                                               }
                                                        }, state);

                _tickTimer?.Change(_renderDueTime, Timeout.Infinite);
            }, null, _renderDueTime, Timeout.Infinite);
        }
コード例 #53
0
        private void CreateForm(Level level)
        {
            _biomeMapForm?.Hide();

            _biomeMapForm              = new BiomeMapForm(level);
            _biomeMapForm.FormClosing += (sender, args) =>
            {
                _timer?.Change(Timeout.Infinite, Timeout.Infinite);
                _biomeMapForm = null;
            };

            _biomeMapForm.Shown += (sender, args) =>
            {
                _timer = new Timer(Update, null, 1000, 1000);
            };

            ThreadPool.QueueUserWorkItem(delegate
            {
                Application.Run(_biomeMapForm);
            });
        }
コード例 #54
0
 void Netcom_ChatReceived(object sender, ChatEventArgs e)
 {
     //somehow it can be too early (when Radegast is loaded from running bot)
     if (instance.GlobalSettings == null)
     {
         return;
     }
     if (!instance.GlobalSettings["disable_look_at"] &&
         e.SourceID != Client.Self.AgentID &&
         (e.SourceType == ChatSourceType.Agent || e.Type == ChatType.StartTyping))
     {
         // change focus max every 4 seconds
         if (Environment.TickCount - lastLookAtEffect > 4000)
         {
             lastLookAtEffect = Environment.TickCount;
             Client.Self.LookAtEffect(Client.Self.AgentID, e.SourceID, Vector3d.Zero, LookAtType.Respond, lookAtEffect);
             // keep looking at the speaker for 10 seconds
             lookAtTimer?.Change(10000, Timeout.Infinite);
         }
     }
 }
コード例 #55
0
        /// <summary>
        /// Execute shutdown tasks
        /// </summary>
        private void Close()
        {
            _timer?.Change(Timeout.Infinite, Timeout.Infinite);

            if (_kinectSource != null)
            {
                _kinectSource.Close();
                _kinectSource = null;
            }

            if (_bodyFrameDumper != null)
            {
                _bodyFrameDumper.Close();
                _bodyFrameDumper = null;
            }

            if (_colorFrameDumper != null)
            {
                _colorFrameDumper.Close();
                _colorFrameDumper = null;
            }
        }
コード例 #56
0
ファイル: GameStats.cs プロジェクト: 71c/Cookie-Clicker
    void Start()
    {
        timer = new System.Threading.Timer(UpdateProperty);
        timer.Change(cookieAddPeriod, cookieAddPeriod);

        zeroCountsToWords.Add(33, "decillion");
        zeroCountsToWords.Add(3, "thousand");
        zeroCountsToWords.Add(36, "undecillion");
        zeroCountsToWords.Add(6, "million");
        zeroCountsToWords.Add(39, "duodecillion");
        zeroCountsToWords.Add(9, "billion");
        zeroCountsToWords.Add(42, "tredecillion");
        zeroCountsToWords.Add(12, "trillion");
        zeroCountsToWords.Add(15, "quadrillion");
        zeroCountsToWords.Add(18, "quintillion");
        zeroCountsToWords.Add(21, "sextillion");
        zeroCountsToWords.Add(24, "septillion");
        zeroCountsToWords.Add(27, "octillion");
        zeroCountsToWords.Add(30, "nonillion");

//		cookies = 123876544m; // testing
    }
コード例 #57
0
        private void processReply(object sender, LineReceivedEventArgs e)
        {
            string reply = e.line;

#if DEBUG
#if DEBUG_JEROME_COMM
            System.Diagnostics.Debug.WriteLine(reply);
#endif
#endif

            if (pingTimer != null)
            {
                pingTimer.Change(timeout, timeout);
            }
            Match match = rEVT.Match(reply);
            if (match.Success)
            {
                int line      = Convert.ToInt16(match.Groups[1].Value);
                int lineState = match.Groups[2].Value == "0" ? 0 : 1;
                Task.Factory.StartNew(() =>
                                      lineStateChanged?.Invoke(this, new LineStateChangedEventArgs {
                    line = line, state = lineState
                }));
            }
            else if (!reply.StartsWith("#SLINF") && !reply.Contains("FLAGS") && !reply.Contains("JConfig"))
            {
                replyTimer?.Change(Timeout.Infinite, Timeout.Infinite);
                if (currentCmd != null && currentCmd.cb != null)
                {
                    Action <string> cb = currentCmd.cb;
                    Task.Factory.StartNew(() => cb.Invoke(reply));
                }
                currentCmd = null;
                processQueue();
            }
        }
コード例 #58
0
ファイル: Timer.cs プロジェクト: DominikHerold/Schwimmkurs
 public void Stop()
 {
     _taskTimer?.Change(Timeout.Infinite, Timeout.Infinite);
 }
コード例 #59
0
 public Task StopAsync(CancellationToken cancellationToken)
 {
     _timer?.Change(Timeout.Infinite, Timeout.Infinite);
     return(Task.CompletedTask);
 }
コード例 #60
0
 public Task StopAsync(CancellationToken cancellationToken)
 {
     //New Timer does not have a stop.
     _timer?.Change(Timeout.Infinite, 0);
     return(Task.CompletedTask);
 }