当前位置: 首页>>代码示例>>C#>>正文


C# Threading.Timer类代码示例

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


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


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