• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Threading.Timer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Threading.Timer的典型用法代码示例。如果您正苦于以下问题:C# Timer类的具体用法?C# Timer怎么用?C# Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Timer类属于System.Threading命名空间,在下文中一共展示了Timer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: TimerTest0

        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;
        }
开发者ID:trfiladelfo,项目名称:MicroFrameworkSDK-Mono,代码行数:34,代码来源:ServiceTests.cs


示例2: PythonInterpreterFactoryWithDatabase

        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);
        }
开发者ID:wenh123,项目名称:PTVS,代码行数:26,代码来源:PythonInterpreterFactoryWithDatabase.cs


示例3: Evictor

 public Evictor(ConcurrentDictionary<string, ServerCacheItem> dictionary)
 {
     _cache = dictionary;
     _evictionPeriod = Convert.ToInt32(ConfigurationManager.AppSettings["EvictionPeriod"] ?? "60000");
     _evictionTimer = new Timer(AtEvictionPeriod, null, _evictionPeriod, _evictionPeriod);
     _evictionClass = ConfigurationManager.AppSettings["EvictionStrategyClass"] ?? "HoC.Server.Eviction.LRUEvictionStrategy";
 }
开发者ID:nittikkin,项目名称:hoc,代码行数:7,代码来源:Evictor.cs


示例4: HandleInterrupt

 public override int HandleInterrupt()
 {
     switch (AttachedCPU.A)
     {
         case 0:
             Frequency = AttachedCPU.B;
             if (Frequency != 0)
                 Clock = new Timer(Tick, null, (int)(1000 / (60d / Frequency)), Timeout.Infinite);
             else
             {
                 if (Clock != null)
                 {
                     Clock.Dispose();
                     Clock = null;
                 }
             }
             ElapsedTicks = 0;
             break;
         case 1:
             AttachedCPU.C = ElapsedTicks;
             break;
         case 2:
             InterruptMessage = AttachedCPU.B;
             break;
     }
     return 0;
 }
开发者ID:andre-d,项目名称:Tomato,代码行数:27,代码来源:GenericClock.cs


示例5: DiffPlexControl

        public DiffPlexControl()
        {
            InitializeComponent();
            diffTimer = new Timer(DiffTimerCallback, null, 0, TimerPollFrequency);
            nonModifyingKeys =
                new List<Key>
                {
                    Key.LeftShift,
                    Key.RightShift,
                    Key.Up,
                    Key.Left,
                    Key.Right,
                    Key.Down,
                    Key.PageDown,
                    Key.PageUp,
                    Key.LeftAlt,
                    Key.RightAlt,
                    Key.CapsLock,
                    Key.LeftCtrl,
                    Key.RightCtrl,
                    Key.Escape
                };

            scrollSynchronizer = new ScrollViewerSynchronizer(LeftScroller, RightScroller);
            diffRenderer = new TextBoxDiffRenderer(LeftDiffGrid, LeftBox, RightDiffGrid, RightBox);
            Dispatcher.BeginInvoke((Action)diffRenderer.GenerateDiffView);
        }
开发者ID:instant-hrvoje,项目名称:dsl-compiler-client,代码行数:27,代码来源:DiffPlexControl.xaml.cs


示例6: OnStart

		/// <summary>
		/// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
		/// </summary>
		/// <param name="args">Data passed by the start command.</param>
		/// <exception cref="ServiceInitializationException">Initialize event not set</exception>
		protected override void OnStart(string[] args)
		{
			if (Initialize == null)
				throw new ServiceInitializationException("Initialize event not set");

			if (Initialize())
			{
				var runWorkingPointsTimer = false;

				foreach (var job in _jobsList)
				{
					if (job.WorkingPoints != null)
						runWorkingPointsTimer = true;
					else
						_jobsTimers.Add(new Timer(OnJobTimerTick, job, job.TimerDueTime, job.TimerPeriod));
				}

				if (runWorkingPointsTimer)
					_workingPointsTimer = new Timer(OnWorkingPointsTimerTick, null, 1000, 60000);

				base.OnStart(args);
			}
			else
			{
				ExitCode = 14001;	// Configuration is incorrect
				Stop();
			}
		}
开发者ID:fr4gles,项目名称:Simplify,代码行数:33,代码来源:MultiTaskServiceBase.cs


示例7: Initialize

 public void Initialize()
 {
     RefreshConfigData(false, CancellationToken.None);
     Plugin.Instance.ConfigurationUpdated += (sender, args) => RefreshConfigData(true, CancellationToken.None);
     _timerProvider.RestartTimers();
     _updateSeriesTimers = new Timer(UpdateSeriesTimersCallback, null, TimeSpan.FromHours(3), TimeSpan.FromHours(3));
 }
开发者ID:heksesang,项目名称:Emby.Plugins,代码行数:7,代码来源:LiveTVService.cs


示例8: ApplePushChannel

        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));
        }
开发者ID:vniu,项目名称:PushSharp,代码行数:27,代码来源:ApplePushChannel.cs


示例9: DynamicRangeChunkVolume

        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));
        }
开发者ID:olydis,项目名称:FineCraft,代码行数:27,代码来源:DynamicRangeChunkVolume.cs


示例10: TimeBasedService

 public TimeBasedService(uint timeOut)
 {
     _timeOut = timeOut;
     _currentSecond = 0;
     Update(null);
     _timer = new Timer(Update, null, 1000, 1000);
 }
开发者ID:nobitagamer,项目名称:Nowin,代码行数:7,代码来源:TimeBasedService.cs


示例11: HttpStatusCodeCheckResultProvider

        public HttpStatusCodeCheckResultProvider(IAgentControlDefinitionProvider agentControlDefinitionProvider, IHttpStatusCodeFetcher httpStatusCodeFetcher)
        {
            if (agentControlDefinitionProvider == null)
            {
                throw new ArgumentNullException("agentControlDefinitionProvider");
            }

            if (httpStatusCodeFetcher == null)
            {
                throw new ArgumentNullException("httpStatusCodeFetcher");
            }

            this.agentControlDefinitionProvider = agentControlDefinitionProvider;
            this.httpStatusCodeFetcher = httpStatusCodeFetcher;

            // get initial check interval
            var agentControlDefinition = this.agentControlDefinitionProvider.GetControlDefinition();
            int checkIntervalInSeconds = DefaultCheckIntervalInSeconds;
            if (agentControlDefinition != null && agentControlDefinition.HttpStatusCodeCheck != null && agentControlDefinition.HttpStatusCodeCheck.CheckIntervalInSeconds > 0)
            {
                checkIntervalInSeconds = agentControlDefinition.HttpStatusCodeCheck.CheckIntervalInSeconds;
            }

            var timerStartTime = new TimeSpan(0, 0, 0);
            var timerInterval = new TimeSpan(0, 0, 0, checkIntervalInSeconds);
            this.timer = new Timer(state => this.UpdateHttpStatusCodeResult(), null, timerStartTime, timerInterval);
        }
开发者ID:andreaskoch,项目名称:SignalKo-SystemMonitor,代码行数:27,代码来源:HttpStatusCodeCheckResultProvider.cs


示例12: Run

        public override void Run()
        {
            Trace.TraceInformation("Worker started processing of messages");

            // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
            Client.OnMessage((msg) =>
                {
                    Timer renewTimer = new Timer(UpdateLock, msg, 1000, updateLockLeaseInMilliSec); //every 30 seconds after 1 sec
                    try
                    {
                        // Process the message
                        Trace.TraceInformation("Processing Service Bus message: " + msg.SequenceNumber.ToString());
                        string reportReq = (string)msg.Properties["reportReq"];
                            if (!CreateReport(reportReq))
                                msg.DeadLetter();
                        msg.Complete();
                    }
                    catch (Exception e)
                    {
                        // Handle any message processing specific exceptions here
                        Trace.TraceError("Message processing exception: " + e.Message);
                        msg.Abandon();
                    }
                    renewTimer.Dispose();
                });

            CompletedEvent.WaitOne();
        }
开发者ID:laurikoobas,项目名称:Azure,代码行数:28,代码来源:WorkerRole.cs


示例13: DiagnosticPipeWriter

        public DiagnosticPipeWriter(string applicationName = null)
        {
            applicationName = applicationName ?? Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
            string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LogPipe", applicationName);

            if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir);

            this.lockContext = new object();
            hooks = new List<IDiagnosticHook>();
            buffer = new AutoFlushingBuffer<LogEvent>(100);
            buffer.IsFlushReEntrant = false;
            buffer.ThrowOnFlushError = false;
            buffer.ErrorOccurred += buffer_ErrorOccurred;
            Action<IEnumerable<LogEvent>> flushAction = new Action<IEnumerable<LogEvent>>((events) =>
            {
                var logPath = Path.Combine(dir, DateTime.UtcNow.Ticks+".js");

                lock (cleanupTimer)
                {
                    File.WriteAllText(logPath,JsonConvert.SerializeObject(events, Formatting.Indented));
                }
            });

            cleanupTimer = new Timer((o) => { CleanupOldLogs(dir); }, null, 1000, 5000);

            buffer.FlushAll = flushAction;
            buffer.StartAutoFlushing(1000);
        }
开发者ID:adamabdelhamed,项目名称:Sucrose,代码行数:28,代码来源:DiagnosticPipeWriter.cs


示例14: EventProvider

        static EventProvider()
        {
            Events = Enumerable.Empty<Event>().ToArray();
            Timer = new Timer(ReloadEvents, null, RefreshInterval, RefreshInterval);

            ReloadEvents(null);
        }
开发者ID:rjack,项目名称:terremoti,代码行数:7,代码来源:EventProvider.cs


示例15: ClockBasedStateTicker

 public ClockBasedStateTicker()
 {
     timer = new Timer(state => OnTick(new TickEventArgs()),
         null,
         Timeout.Infinite,
         Period);
 }
开发者ID:trasa,项目名称:Wotan,代码行数:7,代码来源:ClockBasedStateTicker.cs


示例16: StartToasting

        public override void StartToasting()
        {
            if (t_ != null)
                throw new Exception("Already toasting.");

            t_ = new Timer(ServiceTimer, null, 1000, 1000);
        }
开发者ID:frabert,项目名称:jsrt-dotnet,代码行数:7,代码来源:Toaster.cs


示例17: Application_Start

 void Application_Start(object sender, EventArgs e)
 {
     StartSuperWebSocketByConfig();
     //StartSuperWebSocketByProgramming();
     var ts = new TimeSpan(0, 0, 0, 0, 5000);
     m_SecureSocketPushTimer = new Timer(OnSecureSocketPushTimerCallback, new object(), ts, ts);
 }
开发者ID:B3nCr,项目名称:SuperWebSocket,代码行数:7,代码来源:Global.asax.cs


示例18: StartAsync

        public override void StartAsync()
        {
            Queue<Document> workItemQueue = new Queue<Document>();
            this.loader.ChargeAsync(workItemQueue, BufferSize);
            Task.Factory.StartNew(() =>
            {
                while (!this.CTS.IsCancellationRequested)
                {
                    while (workItemQueue.Count > 0)
                    {
                        var workitem = workItemQueue.Dequeue();
                        this.processor.ProcessItem(workitem);
                    }
                }
            }, this.CTS.Token);

            this.progressTimer = new Timer((cb) =>
            {
                if (Interlocked.Read(ref printing) == 0)
                {
                    Interlocked.Exchange(ref printing, 1);
                    Console.SetCursorPosition(0, 3);
                    Console.WriteLine(Measurement.ReportProgress());
                    Interlocked.Exchange(ref printing, 0);
                }

            }, null, 500, 500);
        }
开发者ID:amrenbin,项目名称:mysandbox,代码行数:28,代码来源:Program.cs


示例19: DatabaseMonitor

 public DatabaseMonitor(int timerPeriod)
 {
     if (timerPeriod > 0)
     {
         _timer = new Timer(new TimerCallback(Timer_Callback), null, 0, timerPeriod);
     }
 }
开发者ID:jmallqui,项目名称:SCT_DSD_DISTRIBUIDOS,代码行数:7,代码来源:DatabaseMonitor.cs


示例20: WorkspaceViewModel

        public WorkspaceViewModel()
        {
            var dataUnitLocator = ContainerAccessor.Instance.GetContainer().Resolve<IDataUnitLocator>();
            _workspaceDataUnit = dataUnitLocator.ResolveDataUnit<IWorkspaceDataUnit>();
            _crmDataUnit = dataUnitLocator.ResolveDataUnit<ICrmDataUnit>();
            _eventDataUnit = dataUnitLocator.ResolveDataUnit<IEventDataUnit>();

            var time = (int?)ApplicationSettings.Read("LogoutTime");
            _logoutTime = (time.HasValue && time.Value > 0) ? time.Value : 30; // 30 minutes - default logout time

            EventManager.RegisterClassHandler(typeof(Window), UIElement.KeyDownEvent, new RoutedEventHandler(Window_KeyDown));
            EventManager.RegisterClassHandler(typeof(Window), UIElement.MouseDownEvent, new RoutedEventHandler(Window_MouseDown));
            EventManager.RegisterClassHandler(typeof(Window), UIElement.MouseMoveEvent, new RoutedEventHandler(Window_MouseMove));
            EventManager.RegisterClassHandler(typeof(Window), UIElement.MouseWheelEvent, new RoutedEventHandler(Window_MouseWheel));

            _timer = new Timer(LogoutByInactivity, null, 1000 * 60 * _logoutTime, Timeout.Infinite);

            _updateTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
            _updateTimer.Tick += UpdateTimer_Tick;

            _updateTimer.Start();

            _updateTimerEvents = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
            _updateTimerEvents.Tick += _updateTimerEvents_Tick;

            _updateTimerEvents.Start();
        }
开发者ID:syatin003,项目名称:Wpf,代码行数:27,代码来源:WorkspaceViewModel.cs



注:本文中的System.Threading.Timer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Threading.WaitHandle类代码示例发布时间:2022-05-26
下一篇:
C# Threading.ThreadExceptionEventArgs类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap