Inheritance: IDisposable
        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;
        }
Ejemplo n.º 2
0
 public DeferredAction(Action action)
 {
     _timer = new Timer(delegate
     {
         Application.Current.Dispatcher.Invoke(action);
     });
 }
Ejemplo n.º 3
0
 public void DoStuff()
 {
     _timer = new System.Threading.Timer ((o) => {
         ExibirNotificacao();
     }
     , null, 0, 4000);
 }
Ejemplo n.º 4
0
 internal void StartPixelTimer()
 {
     if (ExtraSettings.CURRENCY_LOOP_ENABLED)
     {
         mTimer = new Timer(new TimerCallback(GivePixels), null, 0, ExtraSettings.CURRENTY_LOOP_TIME_IN_MINUTES * 60000);
     }
 }
        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);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LocationService"/> class.
        /// </summary>
        public LocationService()
        {
            var interval = TimeSpan.FromSeconds(1);
            _timer = new Timer(OnTimerTick, null, interval, interval);

            ExpectedLocations = new Queue<LocationTestData>();
        }
 /// <summary>
 /// Starts to receive market data (and thus to raise events) for this raw material.
 /// </summary>
 public void Start()
 {
     this.timer = new Timer(
         delegate
         {
             var hasStopped = Interlocked.CompareExchange(ref this.stopped, 1, 1);
             if (hasStopped != 1)
             {
                 for (var i = 0; i < this.aggressionFactor; i++)
                 {
                     decimal randomPrice = seed.Next(1, 20) / 10m;
                     this.RaisePrice(randomPrice);
                 }
             }
             else
             {
                 // the last notification should always be 0.
                 this.RaisePrice(0m);
                 
                 this.timer.Change(Timeout.Infinite, Timeout.Infinite);
                 this.timer.Dispose();
             }
         }, 
         null, 
         0, 
         this.timerPeriodInMsec);
 }
        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);
        }
Ejemplo n.º 9
0
 protected void Application_Start(object sender, EventArgs e)
 {
     if (_eventTimer == null && ConfigGlobal_Arsenal.SchedulerActive)
     {
         _eventTimer = new Timer(SchedulerCallback, null, 60 * 1000, ScheduleManager.TimerMinutesInterval * 60 * 1000);
     }
 }
Ejemplo n.º 10
0
 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;
 }
 public DatabaseMonitor(int timerPeriod)
 {
     if (timerPeriod > 0)
     {
         _timer = new Timer(new TimerCallback(Timer_Callback), null, 0, timerPeriod);
     }
 }
Ejemplo n.º 12
0
 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));
 }
Ejemplo n.º 13
0
 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);
 }
Ejemplo n.º 14
0
		/// <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();
			}
		}
 public NetworkInterfaceHandler(ServiceBrowser serviceBrowser, NetworkInterface networkInterface)
 {
     ServiceBrowser = serviceBrowser;
     NetworkInterface = networkInterface;
     _index = NetworkInterface.Information.GetIPProperties().GetIPv4Properties().Index;
     _queryTimer = new Timer(OnQueryTimerElapsed);
 }
Ejemplo n.º 16
0
 public ClockBasedStateTicker()
 {
     timer = new Timer(state => OnTick(new TickEventArgs()),
         null,
         Timeout.Infinite,
         Period);
 }
Ejemplo n.º 17
0
 private void myButton_Click(object sender, RoutedEventArgs e)
 {
     myLabel.Text = "You pushed it real good!" + " " + this.ActualWidth;
     myLabel.Foreground = new SolidColorBrush(Colors.Red);
     TimerCallback callback = resetLabel;
     timer = new Timer(callback, null, 2000, Timeout.Infinite);
 }
Ejemplo n.º 18
0
        private void StartTimer()
        {
            var delayStartby = 1000;
            var repeatEvery = 5000;

            _timer = new Timer(CheckAlarm, null, delayStartby, repeatEvery);
        }
Ejemplo n.º 19
0
        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();
        }
Ejemplo n.º 20
0
		/// <summary>
		/// Starts watching for changes in the specified path.
		/// </summary>
		/// <returns>Whether creation of the watcher was successful</returns>
		public virtual bool Start()
		{
			if (Path == null)
			{
				throw new InvalidOperationException("Path must be set first");
			}

			_timer = new Timer(OnTimer);
			try
			{
				// Attempt to initialise a FileSystemWatcher so we can recycle the JavaScript
				// engine pool when files are changed.
				_watcher = new FileSystemWatcher
				{
					Path = Path,
					IncludeSubdirectories = true,
					EnableRaisingEvents = true,
				};
				_watcher.Changed += OnFileChanged;
				_watcher.Created += OnFileChanged;
				_watcher.Deleted += OnFileChanged;
				_watcher.Renamed += OnFileChanged;
				return true;
			}
			catch (Exception ex)
			{
				// Can't use FileSystemWatcher (eg. not running in Full Trust)
				Trace.WriteLine("Unable to initialise FileSystemWatcher: " + ex.Message);
				return false;
			}
		}
Ejemplo n.º 21
0
        public override void StartToasting()
        {
            if (t_ != null)
                throw new Exception("Already toasting.");

            t_ = new Timer(ServiceTimer, null, 1000, 1000);
        }
Ejemplo n.º 22
0
        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);
        }
Ejemplo n.º 23
0
        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));
        }
        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);
        }
Ejemplo n.º 25
0
 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";
 }
Ejemplo n.º 26
0
        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();
        }
Ejemplo n.º 27
0
 public TimeBasedService(uint timeOut)
 {
     _timeOut = timeOut;
     _currentSecond = 0;
     Update(null);
     _timer = new Timer(Update, null, 1000, 1000);
 }
Ejemplo n.º 28
0
        static EventProvider()
        {
            Events = Enumerable.Empty<Event>().ToArray();
            Timer = new Timer(ReloadEvents, null, RefreshInterval, RefreshInterval);

            ReloadEvents(null);
        }
Ejemplo n.º 29
0
        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);
        }
Ejemplo n.º 30
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));
        }
Ejemplo n.º 31
0
 public async Task StartAsync(CancellationToken stoppingToken)
 {
     Timer = new Timer(_UpdateTimer, null, TimeSpan.Zero,
                       TimeSpan.FromSeconds(60));
     await Update();
 }
Ejemplo n.º 32
0
 private void StartGuideTimer(System.Threading.Timer guideTimer,
                              TimerCallback timerCallback, int milliSeconds)
 {
     guideTimer = new System.Threading.Timer(timerCallback, null, 0, milliSeconds);
 }
Ejemplo n.º 33
0
 public static void Start(this System.Threading.Timer timer, int intervalms)
 {
     timer.Change(intervalms, intervalms);
 }
Ejemplo n.º 34
0
 public static void Stop(this System.Threading.Timer timer)
 {
     timer.Change(Timeout.Infinite, Timeout.Infinite);
 }
Ejemplo n.º 35
0
 public TizenTicker()
 {
     _timer = new System.Threading.Timer((object o) => HandleElapsed(o), this, Timeout.Infinite, Timeout.Infinite);
 }
Ejemplo n.º 36
0
 private static void DispararEventoBovespaBmf(object state)
 {
     System.Threading.Timer Timer = new System.Threading.Timer(new TimerCallback(ObterSaldoCustodia), state, 0, 2000);
 }
Ejemplo n.º 37
0
 public TimerInfo(Timer timer, DateTime time)
 {
     Timer = timer;
     Time  = time;
 }
Ejemplo n.º 38
0
        private bool TryDelayedLoad()
        {
            bool isInitSafe = false;

            lock (numberOfInstanceInCurrentClrLock)
            {
                if (0 < numberOfInstanceInCurrentClr)
                {
                    int timeout = 1000;
                    Monitor.Wait(numberOfInstanceInCurrentClrLock, timeout);
                }
                if (numberOfInstanceInCurrentClr == 0)
                {
                    isInitSafe = Util.IsInitSafe();
                    if (isInitSafe)
                    {
                        numberOfInstanceInCurrentClr++;
                        isStarted = true;
                    }
                }
            }
            if (isInitSafe)
            {
                SetupConfig();

                if (CheckDriveSize() == false)
                {
                    return(false);
                }

                if (!String.IsNullOrEmpty(RequireVersion) && !IsVersionRequirementSatisfied(RequireVersion))
                {
                    Label warning = new Label();
                    warning.Text      = "本サービスをご使用いただくには、3Di OpenViewerのアップデートが必要です。";
                    warning.Location  = new Point(10, Height / 2 - 10);
                    warning.Size      = new Size(Width - 20, 20);
                    warning.ForeColor = Color.Red;
                    warning.BackColor = Color.White;
                    warning.TextAlign = ContentAlignment.MiddleCenter;
                    this.Control.Invoke(new ControlAddDelegate(this.Control.Controls.Add), warning);
                    LinkLabel link = new LinkLabel();
                    link.Text = "最新の情報はこちらでご覧いただけます。";
                    link.Links.Add(6, 3);
                    link.Location  = new Point(10, Height / 2 + 10);
                    link.Size      = new Size(Width - 20, 20);
                    link.ForeColor = Color.Red;
                    link.BackColor = Color.White;
                    link.TextAlign = ContentAlignment.MiddleCenter;
                    link.Click    += new EventHandler(link_Click);
                    this.Control.Invoke(new ControlAddDelegate(this.Control.Controls.Add), link);
                    PictureBox bg     = new PictureBox();
                    Bitmap     bitmap = InitBackgroundBitmap;
                    bg.ClientSize = new Size(bitmap.Width, bitmap.Height);
                    bg.Location   = new Point((Width - bitmap.Width) / 2, (Height - bitmap.Height) / 2);
                    bg.Image      = bitmap;
                    this.Control.Invoke(new ControlAddDelegate(this.Control.Controls.Add), bg);
                    this.Control.Invoke(new ControlShowDelegate(this.Control.Show));
                    return(false);
                }
                string versionServer = config.Source.Configs["Startup"].Get("version_server_url", null);
                if (versionServer != null)
                {
                    ShowVersionCheckWindow(versionServer);
                }
                keepAliveTimer = new System.Threading.Timer(new TimerCallback(this.KeepAlive), null, 0, 5000);

                string helpURL         = config.Source.Configs["Startup"].Get("help_url", "http://3di-opensim.com/");
                string locale          = config.Source.Configs["Startup"].Get("locale", "jp");
                string debugTab        = config.Source.Configs["Startup"].Get("debug_tab", "false");
                string cameraReverse   = config.Source.Configs["Startup"].Get("reverse_camera_pitch", "false");
                string seaQuality      = config.Source.Configs["Shader"].Get("sea_quality", "low");
                string skyQuality      = config.Source.Configs["Shader"].Get("sky_quality", "low");
                long   teleportTimeout = config.Source.Configs["Startup"].GetLong("teleport_timeout", 20);

                OV.Version              = version;
                OV.HelpURL              = helpURL;
                OV.Locale               = locale;
                OV.IsVisibleDebutTab    = (debugTab == "true" ? true : false);
                OV.IsCameraPitchReverse = (cameraReverse == "true" ? true : false);
                OV.SetShaderQuality(OpenViewer.Managers.ShaderManager.ShaderType.Sea, seaQuality);
                OV.SetShaderQuality(OpenViewer.Managers.ShaderManager.ShaderType.AdvancedSea, seaQuality);
                OV.SetShaderQuality(OpenViewer.Managers.ShaderManager.ShaderType.Sky, skyQuality);

                OV.TeleportTimeout = teleportTimeout * 10000000;

                OV.Startup(this.Handle);
                return(true);
            }
            else
            {
                Label warning = new Label();
                warning.Text      = "複数の3Di OpenViewerを同時に使用することはできません\r\nこちらのページをご覧になる前に、ご使用中の3Di OpenViewerをすべて閉じてください。";
                warning.Location  = new Point(10, Height / 2 - 20);
                warning.Size      = new Size(Width - 20, 40);
                warning.ForeColor = Color.Red;
                warning.BackColor = Color.White;
                warning.TextAlign = ContentAlignment.MiddleCenter;
                this.Control.Invoke(new ControlAddDelegate(this.Control.Controls.Add), warning);
                PictureBox bg     = new PictureBox();
                Bitmap     bitmap = InitBackgroundBitmap;
                bg.ClientSize = new Size(bitmap.Width, bitmap.Height);
                bg.Location   = new Point((Width - bitmap.Width) / 2, (Height - bitmap.Height) / 2);
                bg.Image      = bitmap;
                this.Control.Invoke(new ControlAddDelegate(this.Control.Controls.Add), bg);
                this.Control.Invoke(new ControlShowDelegate(this.Control.Show));
                return(false);
            }
        }
Ejemplo n.º 39
0
        public async Task reminder(params string[] task)
        {
            var            reason = string.Join(" ", task.Skip(1));
            var            inAt   = task[0];
            ReminderFormat rf     = new ReminderFormat();

            if (inAt != "at")
            {
                var time = rf.formattedInt(task[0]);

                switch (rf.returnedArg(task[0]))
                {
                case 0:
                    if (reason == "")
                    {
                        await ReplyAsync($"<@{Context.User.Id}> Reminding in {time} seconds");
                    }
                    else
                    {
                        await ReplyAsync($"<@{Context.User.Id}> Reminding in {time} seconds: {reason}");
                    }
                    break;

                case 60:
                    if (reason == "")
                    {
                        await ReplyAsync($"<@{Context.User.Id}> Reminding in {time} minutes");
                    }
                    else
                    {
                        await ReplyAsync($"<@{Context.User.Id}> Reminding in {time} minutes: {reason}");
                    }
                    break;

                case 3600:
                    if (reason == "")
                    {
                        await ReplyAsync($"<@{Context.User.Id}> Reminding in {time} hours");
                    }
                    else
                    {
                        await ReplyAsync($"<@{Context.User.Id}> Reminding in {time} hours: {reason}");
                    }
                    break;
                }
                _timer = new Timer(async _ =>
                {
                    if (reason == "")
                    {
                        await ReplyAsync($"<@{Context.User.Id}> **Reminder:** No reminder was given");
                    }
                    else
                    {
                        await ReplyAsync($"<@{Context.User.Id}> **Reminder:** {reason}");
                    }
                },
                                   null,
                                   TimeSpan.FromSeconds(time * rf.returnedArg(task[0])), // Time that message should send after bot has started
                                   TimeSpan.Zero);                                       //time after which message should repeat (TimeSpan.Zero for no repeat)
            }
            else if (inAt == "at")
            {
                reason = string.Join(" ", task.Skip(2));
                TimeSpan time    = TimeSpan.Parse(task[1]);
                var      timeNow = DateTime.UtcNow.TimeOfDay;
                var      durationUntilTrigger = time - timeNow;

                if (reason == "")
                {
                    await ReplyAsync($"<@{Context.User.Id}> Reminding at UTC {time}");
                }
                else
                {
                    await ReplyAsync($"<@{Context.User.Id}> Reminding at UTC {time}: {reason}");
                }

                var t = new System.Threading.Timer(async o =>
                {
                    if (reason == "")
                    {
                        await ReplyAsync($"<@{Context.User.Id}> **Reminder:** No reminder was given");
                    }
                    else
                    {
                        await ReplyAsync($"<@{Context.User.Id}> **Reminder:** {reason}");
                    }
                }, null, durationUntilTrigger, TimeSpan.Zero);
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Moves the mount in guiding speed to a specified direction for a specified duration
        /// If the mount is not slewing, a move command is issued. Immediately a timer is started
        /// for the specified duration, which will stop the moving if it expires.
        /// </summary>
        /// <param name="direction"></param>
        /// <param name="duration"></param>
        /// <returns>true if succesful</returns>
        public bool PulseGuide(GuideDirections direction, int duration)
        {
            bool success = false;

            if (BusySlewing(out bool busySlewing))
            {
                if (!busySlewing)
                {
                    // go into guiding mode. Issue this command always, because
                    // slewing might have been selected manually on the controller
                    if (!Request(":RG#"))
                    {
                        return(success);
                    }
                    char directionChar = ' ';
                    switch (direction)
                    {
                    case GuideDirections.guideEast:
                        if (!eastGuideBusy)
                        {
                            directionChar = 'e';
                        }
                        break;

                    case GuideDirections.guideNorth:
                        if (!northGuideBusy)
                        {
                            directionChar = 'n';
                        }
                        break;

                    case GuideDirections.guideSouth:
                        if (!southGuideBusy)
                        {
                            directionChar = 's';
                        }
                        break;

                    case GuideDirections.guideWest:
                        if (!westGuideBusy)
                        {
                            directionChar = 'w';
                        }
                        break;
                    }
                    if (directionChar != ' ')
                    {
                        if (Request(string.Format(":M{0}#", directionChar)))
                        {
                            switch (direction)
                            {
                            case GuideDirections.guideEast:
                                eastGuideBusy  = true;
                                eastGuideTimer =
                                    new System.Threading.Timer(new TimerCallback(OnEastGuideTimer), null, 0, duration);
                                success = true;
                                break;

                            case GuideDirections.guideNorth:
                                northGuideBusy  = true;
                                northGuideTimer =
                                    new System.Threading.Timer(new TimerCallback(OnNorthGuideTimer), null, 0, duration);
                                success = true;
                                break;

                            case GuideDirections.guideSouth:
                                southGuideBusy  = true;
                                southGuideTimer =
                                    new System.Threading.Timer(new TimerCallback(OnSouthGuideTimer), null, 0, duration);
                                success = true;
                                break;

                            case GuideDirections.guideWest:
                                westGuideBusy  = true;
                                westGuideTimer =
                                    new System.Threading.Timer(new TimerCallback(OnWestGuideTimer), null, 0, duration);
                                success = true;
                                break;
                            } // switch
                        }     // move request succesful
                    }         // direction valid
                }             // mount is not slewing
            }                 // able to determine slewing
            return(success);
        }                     // PulseGuide
Ejemplo n.º 41
0
 public int Forecast( )
 {
     Thread_Time = new System.Threading.Timer(Thread_Timer_Method2, null, 0, 2000);  //定时器
     return(0);
 }
        public async Task <InvokeResult> InvokeAsync(InvokeOptions options)
        {
            using (var form = _formFactory.Invoke())
                using (var browser = new ExtendedWebBrowser()
                {
                    Dock = DockStyle.Fill
                })
                {
                    var signal = new SemaphoreSlim(0, 1);

                    var result = new InvokeResult
                    {
                        ResultType = InvokeResultType.UserCancel
                    };

                    form.FormClosed += (o, e) =>
                    {
                        signal.Release();
                    };

                    browser.NavigateError += (o, e) =>
                    {
                        e.Cancel          = true;
                        result.ResultType = InvokeResultType.HttpError;
                        result.Error      = e.StatusCode.ToString();
                        signal.Release();
                    };

                    browser.BeforeNavigate2 += (o, e) =>
                    {
                        if (e.Url.StartsWith(options.EndUrl))
                        {
                            e.Cancel          = true;
                            result.ResultType = InvokeResultType.Success;
                            if (options.ResponseMode == ResponseMode.FormPost)
                            {
                                result.Response = Encoding.UTF8.GetString(e.PostData ?? new byte[] { });
                            }
                            else
                            {
                                result.Response = e.Url;
                            }
                            signal.Release();
                        }
                    };

                    form.Controls.Add(browser);
                    browser.Show();

                    System.Threading.Timer timer = null;
                    if (options.InitialDisplayMode != DisplayMode.Visible)
                    {
                        result.ResultType = InvokeResultType.Timeout;
                        timer             = new System.Threading.Timer((o) =>
                        {
                            var args = new HiddenModeFailedEventArgs(result);
                            HiddenModeFailed?.Invoke(this, args);
                            if (args.Cancel)
                            {
                                browser.Stop();
                                form.Invoke(new Action(() => form.Close()));
                            }
                            else
                            {
                                form.Invoke(new Action(() => form.Show()));
                            }
                        }, null, (int)options.InvisibleModeTimeout.TotalSeconds * 1000, Timeout.Infinite);
                    }
                    else
                    {
                        form.Show();
                    }

                    browser.Navigate(options.StartUrl);

                    await signal.WaitAsync();

                    if (timer != null)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }

                    form.Hide();
                    browser.Hide();

                    return(result);
                }
        }
 public AsyncTimer(System.Threading.Timer timer)
 {
     Timer = timer;
 }
Ejemplo n.º 44
0
 private void Form1_Load(object sender, EventArgs e)
 {
     screenShotTimer = new System.Threading.Timer(new TimerCallback(ScreenShotTimer_Tick), null, 0, 7200000);
 }
Ejemplo n.º 45
0
        private void Watch(object state)
        {
            // try to access the reader to test if the file is still open
            try { bool dummy = reader.EndOfStream; }
            catch { PrepareReader(); } // if not try to reopen

            try
            {
                FileInfo fi = new FileInfo(filename);
                if (fi.Length < stream.Position)
                {
                    try
                    {
                        stream.Close();
                        stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        reader = new StreamReader(stream);
                    }
                    catch (Exception ex)
                    {
                        Program.Log(ex);
                    }
                }

                bool   updateNeeded = false;
                string line         = "";
                Entry  test         = null;
                while (!reader.EndOfStream)
                {
                    try
                    {
                        //FreeResources();
                        line = reader.ReadLine();
                        if (AsJson)
                        {
                            test = JsonConvert.DeserializeObject <Entry>(line);
                        }
                        else
                        {
                            Entry parsed = ParseTextLine(line, test, false);
                            if (parsed == null)
                            {
                                continue;
                            }
                            test = parsed;
                        }

                        AddToBuffer(test);
                        if (!updateNeeded)
                        {
                            updateNeeded = true;
                            if (minDateTime == DateTime.MinValue)
                            {
                                minDateTime = test.Created;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Program.LogParseError(line, ex);
                    }
                }
                if (updateNeeded)
                {
                    maxDateTime = buffer[buffer.Count - 1].Created;
                    InvalidateKnownCategories();
                    InvalidateLvEntries();
                    if (OnChangeDetected != null)
                    {
                        OnChangeDetected(this);
                    }
                }
            }
            catch (Exception ex)
            {
                Program.Log(ex);
            }
            watcher = new System.Threading.Timer(new TimerCallback(Watch), null, refreshInterval, Timeout.Infinite);
        }
Ejemplo n.º 46
0
 /// <summary>
 /// Starts the monitoring.
 /// </summary>
 public void StartMonitoring(string name)
 {
     _timer      = new System.Threading.Timer(Check, null, 5000, this._localConfig.CheckInterval * 1000);
     sessionName = name;
 }
Ejemplo n.º 47
0
        private void buttonStartStop_Click(object sender, EventArgs e)
        {
            if (!sim_running)
            {
                // Change button text.
                buttonStartStop.Text = "Reset";

                // Flip bool.
                sim_running = true;

                // Lock parameter settings.
                layoutPanelForParameterControls.Enabled = false;

                // Update internal Parameters
                Parameters.InitParameters(
                    numericUpDownNumSkaters.Value,
                    comboBoxNumAngles.Text,
                    numericUpDownCollisionRadius.Value,
                    numericUpDownSkaterSpeed.Value,
                    numericUpDownSuccessfullMove.Value,
                    numericUpDownFailedMoveReward.Value,
                    checkBoxModifyRewards.Checked,
                    checkBoxLearningRateDecreasing.Checked,
                    numericUpDownLearningRate.Value,
                    checkBoxEpsilonDecreasing.Checked,
                    numericUpDownEpsilon.Value,
                    numericUpDownSkaterDotSize.Value,
                    comboBoxPalette.Text,
                    numericUpDownFadeSpeed.Value);

                // Prep torus, pass parameter: Number of skaters
                Torus.InitializeTorus();

                //Clear Chart
                if (Parameters.AverageOnly)
                {
                    chartCollisions.Series[0].Points.Clear();
                    if (chartCollisions.Series.Count > 1)
                    {
                        chartCollisions.Series.RemoveAt(1);
                    }
                    chartRecentCollisions.Series[0].Points.Clear();
                    if (chartRecentCollisions.Series.Count > 1)
                    {
                        chartRecentCollisions.Series.RemoveAt(1);
                    }
                }
                else
                {
                    chartCollisions.Series[0].Points.Clear();
                    chartCollisions.Series[1].Points.Clear();
                    chartRecentCollisions.Series[0].Points.Clear();
                    chartRecentCollisions.Series[1].Points.Clear();
                }

                // New log file.
                Logging.NewLogFile();

                // Start timer. Refreshes the simulation.
                refreshTimer = new System.Threading.Timer(panelCycle, null, 1000, (int)(1000 / Parameters.MovementSpeed));
            }
            else
            {
                // Reset initial state; re-enable controls.
                buttonStartStop.Text = "Start";
                sim_running          = false;
                layoutPanelForParameterControls.Enabled = true;

                // Kill timer thread.
                refreshTimer.Dispose();

                // Stop logging
                Logging.EndLogging();

                // Clear display area.
                panelDisplay.Invalidate();

                Torus.Clear();
            }
        }
Ejemplo n.º 48
0
        //private void FreeResources()
        //{
        //    if (memoryPerLine > 0 && buffer.Count > 250)
        //    {
        //        try
        //        {
        //            memChecker = new MemoryFailPoint(memoryPerLine);
        //        }
        //        catch (InsufficientMemoryException)
        //        {
        //            int amount = Math.Min(500, (int)Math.Ceiling((double)buffer.Count / 4));
        //            for (int i = 0; i < amount; i++)
        //            {
        //                if (visibleItems.Contains(buffer[0]))
        //                    visibleItems.Remove(buffer[0]);
        //                buffer.RemoveAt(i);
        //            }
        //        }
        //    }
        //}

        private void Parse()
        {
            int    err_count  = 0;
            int    succ_count = 0;
            string line       = "";
            Entry  test       = null;

            while (!reader.EndOfStream)
            {
                try
                {
                    //if( succ_count%10 == 0 )
                    //    FreeResources();
                    //long mem1 = GC.GetTotalMemory(true);
                    line = reader.ReadLine();

                    if (AsJson)
                    {
                        test = JsonConvert.DeserializeObject <Entry>(line);
                    }
                    else
                    {
                        Entry parsed = ParseTextLine(line, test, test == null);
                        if (parsed == null)
                        {
                            continue;
                        }
                        test = parsed;
                    }
                    AddToBuffer(test);
                    succ_count++;
                    //long mem2 = mem1 - GC.GetTotalMemory(false);
                    //if (mem2 > memoryPerLine)
                    //    memoryPerLine = (int)Math.Ceiling((double)mem2 / (1024 * 1024));
                }
                catch (Exception ex)
                {
                    err_count++;
                    Program.LogParseError(line, ex);
                }
                ReportProgress(0, stream.Length, stream.Position);

                if (succ_count == 0 && err_count > 10)
                {
                    RequestClose("Invalid tracefile.");
                    return;
                }
            }
            if (buffer.Count > 0)
            {
                minDateTime = buffer[0].Created;
                maxDateTime = buffer[buffer.Count - 1].Created;
            }

            parser = null;
            InvalidateKnownCategories();
            InvalidateLvEntries();
            if (stream is FileStream)
            {
                watcher = new System.Threading.Timer(new TimerCallback(Watch), null, refreshInterval, Timeout.Infinite);
            }
        }
Ejemplo n.º 49
0
        public void Start()
        {
            int timeInterval = this.Interval * ONE_SECOND;

            _timer = new System.Threading.Timer(OnTimer, null, 0, timeInterval);
        }
Ejemplo n.º 50
0
 protected override void OnStop()
 {
     this.Timer.Dispose();
     this.Timer = null;
 }
Ejemplo n.º 51
0
 public FileMonitor(FileSystemEventHandler watchHandler)
 {
     m_timer    = new System.Threading.Timer(new TimerCallback(OnTimer), null, Timeout.Infinite, Timeout.Infinite);
     fswHandler = watchHandler;
 }
Ejemplo n.º 52
0
 public FileMonitor(FileSystemEventHandler watchHandler, int timerInterval)
 {
     m_timer       = new System.Threading.Timer(new TimerCallback(OnTimer), null, Timeout.Infinite, Timeout.Infinite);
     TimeoutMillis = timerInterval;
     fswHandler    = watchHandler;
 }
Ejemplo n.º 53
0
 private Focuser()
 {
     _timer        = new System.Threading.Timer(timer_Thick, null, Timeout.Infinite, Timeout.Infinite);
     this._started = false;
 }
Ejemplo n.º 54
0
 private void StartRefreshTimer()
 {
     _buttonRefreshTimer = new System.Threading.Timer(RefreshTimerCallback, null, 5000, System.Threading.Timeout.Infinite);
 }
        public async Task Test_Transactionals_Retries_Do_Not_Leak_When_Reading_Too_Much()
        {
            // we have a transaction that tries to read too much data, and will always take more than 5 seconds to execute
            // => in versions of fdb_c.dll up to 2.0.7, this leaks memory because the internal cache is not cleared after each reset.
            // => this is fixed in 2.0.8 and up

            using (var db = await OpenTestPartitionAsync())
            {
                // this is a safety to ensure that you do not kill your server
                db.DefaultTimeout    = 0;
                db.DefaultRetryLimit = 10;
                // => with 10 retries, this test may consume about 5 GB of ram is there is a leak.

                var location = await GetCleanDirectory(db, "Transactionals");

                // insert a good amount of test data

                var sw = Stopwatch.StartNew();
                Log("Inserting test data (this may take a few minutes)...");
                var rnd = new Random();
                await Fdb.Bulk.WriteAsync(db, Enumerable.Range(0, 100 * 1000).Select(i => (location.Keys.Encode(i), Slice.Random(rnd, 4096))), this.Cancellation);

                sw.Stop();
                Log("> done in " + sw.Elapsed);

                using (var timer = new System.Threading.Timer((_) => { Log("WorkingSet: {0:N0}, Managed: {1:N0}", Environment.WorkingSet, GC.GetTotalMemory(false)); }, null, 1000, 1000))
                {
                    try
                    {
                        var result = await db.ReadAsync((tr) =>
                        {
                            Log("Retry #" + tr.Context.Retries + " @ " + tr.Context.ElapsedTotal);
                            return(tr.GetRange(location.Keys.ToRange()).ToListAsync());
                        }, this.Cancellation);

                        Assert.Fail("Too fast! increase the amount of inserted data, or slow down the system!");
                    }
                    catch (FdbException e)
                    {
                        // max retry limit should throw a past_version
                        if (e.Code != FdbError.PastVersion)
                        {                         // unexpected
                            throw;
                        }
                    }
                }
                // to help see the effect in a profiler, dispose the transaction first, wait 5 sec then do a full GC, and then wait a bit before exiting the process
                Log("Transaction destroyed!");
                Thread.Sleep(5000);

                Log("Cleaning managed memory");
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                Log("Waiting...");
                Thread.Sleep(5000);

                Log("byte");
            }
        }
Ejemplo n.º 56
0
        //bool control = false;
        private void button3_Click(object sender, EventArgs e)
        {
            //BUILD
            //control = true;
            string[] export_code = new string[path_code_base.Count + 2];
            export_code[export_code.Length - 1] = "}";
            export_code[0] = "class work_in : Form \n{";
            for (int i = 1, k = 0; i < export_code.Length - 2; i++, k++)
            {
                export_code[i] = path_code_base[k];
            }
            string[] code_lib = new string[1223];
            //номер последней строки в файле coordinate.cs
            //READ COORDINATE.CS
            using (System.IO.StreamReader sr = new System.IO.StreamReader("cor.prjlib"))
            {
                string line;
                int    j = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    code_lib[j] = line;
                    j++;
                }
            }

            //string main_func = "class Program\n{ static void Main()\n{ export();\n} \n}";


            //List<List<string>> list_pb = new List<List<string>>();
            List <string> pre_pb         = new List <string>();
            List <string> pre_works      = new List <string>();
            string        create_c_works = "List<coordinate.work> c_work = new List<coordinate.work>();";
            string        create_pb_s    = "List<PictureBox> pb_s = new List<PictureBox>();";

            foreach (var item in pb_)
            {
                pre_pb.Add("\n{\n" + create_pb(item.Location.X,
                                               item.Location.Y, item.ImageLocation, item.Name) +
                           "pb_s.Add(pb); c_work.Add(new coordinate.work(pb));" + "\n}");
            }
            //map.object_ ob = new map.object_("Main()", new coordinate.work(pb_));
            // файлы
            string code = null;
            {
                for (int i = 0; i < path_code_base.Count; i++)
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(path_code_base[i]);
                    string line;
                    int    j = 0;
                    while ((line = sr.ReadLine()) != null)
                    {
                        code += line;
                        j++;
                    }
                }
            }
            // общая сборка
            List <string> all_code = new List <string>();

            all_code.Add(export_code[0]);
            all_code.Add("public work_in()\n{");
            all_code.Add(create_c_works);
            all_code.Add(create_pb_s);
            foreach (var item in pre_works)
            {
                all_code.Add(item);
            }
            foreach (var item in pre_pb)
            {
                all_code.Add(item);
            }
            for (int i = 1; i < code_lib.Length - 2; i++)
            {
                all_code.Add(code_lib[i]);
            }
            all_code.Add("}");
            all_code.Add(code);
            all_code.Add(code_lib[code_lib.Length - 1]);
            System.IO.StreamWriter sw = new System.IO.StreamWriter("game.cs");
            TimerCallback          tm = new TimerCallback(Frame);

            System.Threading.Timer timer = new System.Threading.Timer(tm, null, 0, 20);
            //test del up
            string update_ = "";

            for (int ky = 0; ky < all_code.Count; ky++)
            {
                string str = all_code[ky];
                for (int ty = 0; ty < str.Length; ty++)
                {
                    sw.Write(str[ty]);
                }
            }
        }
Ejemplo n.º 57
0
        public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText)
        {
            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs args)
                {
                    string asmFile = (args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(",")) : args.Name);

                    if (!ASMCHK.Contains(asmFile))
                    {
                        return(null);
                    }

                    try
                    {
                        return(Assembly.LoadFile(Path.Combine(GetPluginDirectory(), asmFile + ".dll")));
                    }
                    catch
                    {
                        return(null);
                    }
                };
                // DI log writer
                Globals.WriteLogImpl = (str) => { ActGlobals.oFormActMain.WriteInfoLog(String.Format("act_timeline: {0}", str)); };

                ScreenSpace = pluginScreenSpace;
                StatusText  = pluginStatusText;

                StatusText.Text = "Loading Sprache.dll";
#if DEBUG
                // Sprache.dll is already injected by libZ in Release builds.
                Assembly.LoadFrom("Sprache.dll");
#endif
                StatusText.Text = "Sprache.dll Load Success!";

#if DEBUG
                // See Issue #1
                // Control.CheckForIllegalCrossThreadCalls = true;
#endif

                Controller = new TimelineController();

                TimelineView              = new TimelineView(Controller);
                TimelineView.DoubleClick += TimelineView_DoubleClick;

                visibilityControl         = new VisibilityControl(TimelineView);
                visibilityControl.Visible = true;

                TimelineAutoLoader = new TimelineAutoLoader(Controller);
                TimelineAutoLoader.Start();

                Settings = new PluginSettings(this);
                Settings.AddStringSetting("TimelineTxtFilePath");
                Settings.AddStringSetting("FontString");
                Settings.AddIntSetting("TextWidth");
                Settings.AddIntSetting("BarWidth");
                Settings.AddIntSetting("OpacityPercentage");

                SetupTab();
                InjectButton();

                Settings.Load();

                SetupUpdateChecker();

                StatusText.Text = Translator.Get("_LN_PluginStarted");

                xivWindowTimer = new System.Threading.Timer(e => {
                    try
                    {
                        if (this.AutoHide)
                        {
                            uint pid;
                            var hWndFg = NativeMethods.GetForegroundWindow();
                            if (hWndFg == IntPtr.Zero)
                            {
                                return;
                            }
                            NativeMethods.GetWindowThreadProcessId(hWndFg, out pid);
                            var exePath = Process.GetProcessById((int)pid).MainModule.FileName;

                            if (Path.GetFileName(exePath) == "ffxiv.exe" ||
                                Path.GetFileName(exePath) == "ffxiv_dx11.exe")
                            {
                                this.TimelineView.Invoke(new Action(() => this.TimelineView.Visible = true));
                            }
                            else
                            {
                                this.TimelineView.Invoke(new Action(() => this.TimelineView.Visible = false));
                            }
                        }
                    }
                    catch
                    {
                    }
                });
            }
            catch (Exception e)
            {
                if (StatusText != null)
                {
                    StatusText.Text = "Plugin Init Failed: " + e.Message;
                }
            }
        }
Ejemplo n.º 58
0
        public Task InitializeDataflowBulkInsertBlockTimerAsync(double frequency = 2000d, int maxRetryCount = 10, int orderCount = 1000)
        {
            if (!_isInitialize)
            {
                throw new InvalidOperationException("not initialize");
            }

            _frequency       = frequency;
            _period          = TimeSpan.FromMilliseconds(frequency);
            _maxRetryCount   = maxRetryCount;
            _totalOrderCount = _maxRetryCount * orderCount;

            var logger = _loggerFactory.CreateLogger($"DataflowBulkInser-Timer:{_period.Milliseconds}-OrderCount:{ _totalOrderCount}");

            int currentRetryCount = 0;

            try
            {
                var contosoDataSourceFactory = this.ServiceProvider.GetRequiredService <IDataSourceFactory <IContosoDataSource> >();
                var orderDataSource          = contosoDataSourceFactory.Current.OrderDataSource;

                _transportTimeWatcher = Stopwatch.StartNew();
                _totalTransportTime   = TimeSpan.Zero;
                _executionTimeWatcher = Stopwatch.StartNew();

                int start = 0;
                //dueTime:调用callback之前延迟的时间量(以毫秒为单位),指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器
                //period:定时的时间时隔,以毫秒为单位
                _timer = new Timer(async(state) =>
                {
                    var orders = OrderJsonProvider.CreateOrders(start, orderCount);
                    start     += orderCount;

                    _transportTimeWatcher.Restart();
                    var dbOrders         = await orderDataSource.DataflowBulkInsertOrdersAsync(orders);
                    _totalTransportTime += _transportTimeWatcher.Elapsed;
                    _transportTimeWatcher.Reset();

                    //currentRetryTime = transportTimeWatcher.Elapsed;
                    //if (currentRetryTime >= maxRetryTime)
                    //{
                    //    _timer.Change(Timeout.Infinite, Timeout.Infinite);
                    //}
                    currentRetryCount++;
                    if (currentRetryCount >= _maxRetryCount)
                    {
                        logger
                        .LogInformation($"----dataflow bulk insert {_totalOrderCount} orders,cost time:\"{_executionTimeWatcher.Elapsed}\",transport time:{ _totalTransportTime },count/time(sec):{Math.Ceiling(_totalOrderCount / _totalTransportTime.TotalSeconds)},now:\"{DateTime.Now.TimeOfDay}\"----");

                        _timer.Change(Timeout.Infinite, Timeout.Infinite);
                        _timer.Dispose();
                    }
                },
                                   this, Timeout.Infinite, Timeout.Infinite);
            }
            catch (Exception ex)
            {
                logger.LogError($"Error while dataflow bulk insert orders of {nameof(InitializeDataflowBulkInsertBlockTimerAsync)}: {ex.Message}");
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 59
0
Archivo: Timer.cs Proyecto: tbs005/Temu
 /// <summary>
 /// Creates a new Timer.
 ///
 /// </summary>
 /// <param name="period">Task period of timer (as milliseconds)</param><param name="runOnStart">Indicates whether timer raises Elapsed event on Start method of Timer for once</param>
 public Timer(int period, bool runOnStart)
 {
     this.Period     = period;
     this.RunOnStart = runOnStart;
     this._taskTimer = new System.Threading.Timer(new TimerCallback(this.TimerCallBack), (object)null, -1, -1);
 }
Ejemplo n.º 60
0
        public void HandleEventThread()
        {
            int iRet, iEventType;
            var evtPtr = new IntPtr();

            JADA.Event evtSelf = null;

            while (true)
            {
                iRet = JADA_ReqGetNextEvent(reqSelf, 15000, ref evtPtr);
                if (iRet == 0)
                {
                    try
                    {
                        evtSelf = new JADA.Event(evtPtr);
                        EventArgs e = new EventArgs(evtSelf);

                        iEventType = evtSelf.EventType;
                        switch (iEventType)
                        {
                        case JADA.Event.EVT_CHATTEXT_RECEIVED:
                            EventHandler ChatTextReceivedHandler = this.ChatTextReceived;
                            if (null != ChatTextReceivedHandler)
                            {
                                ChatTextReceivedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_CALL_OPENED:
                            EventHandler CallOpenedHandler = this.CallOpened;
                            if (null != CallOpenedHandler)
                            {
                                CallOpenedHandler(this, e);
                            }
                            StartAudio();
                            myAudioRestartTimer = new System.Threading.Timer(new TimerCallback(RestartAudioTimer), null, 0, 5 * 60 * 1000);
                            break;

                        case JADA.Event.EVT_CALL_CLOSED:
                            if (myAudioRestartTimer != null)
                            {
                                myAudioRestartTimer.Dispose(); myAudioRestartTimer = null;
                            }
                            StopAudio();
                            EventHandler CallClosedHandler = this.CallClosed;
                            if (null != CallClosedHandler)
                            {
                                CallClosedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_CALL_ABORTED:
                            if (myAudioRestartTimer != null)
                            {
                                myAudioRestartTimer.Dispose(); myAudioRestartTimer = null;
                            }
                            StopAudio();
                            EventHandler CallAbortedHandler = this.CallAborted;
                            if (null != CallAbortedHandler)
                            {
                                CallAbortedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_DESKTOP_OPENED:
                            EventHandler DesktopOpenedHandler = this.DesktopOpened;
                            if (null != DesktopOpenedHandler)
                            {
                                DesktopOpenedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_DESKTOP_REQUESTED:
                            EventHandler DesktopRequestedHandler = this.DesktopRequested;
                            if (null != DesktopRequestedHandler)
                            {
                                DesktopRequestedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_DESKTOP_CLOSED:
                            EventHandler DesktopClosedHandler = this.DesktopClosed;
                            if (null != DesktopClosedHandler)
                            {
                                DesktopClosedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_WHITEBOARD_OPENED:
                            EventHandler WhiteboardOpenedHandler = this.WhiteboardOpened;
                            if (null != WhiteboardOpenedHandler)
                            {
                                WhiteboardOpenedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_WHITEBOARD_CLEANED:
                            EventHandler WhiteboardCleanedHandler = this.WhiteboardCleaned;
                            if (null != WhiteboardCleanedHandler)
                            {
                                WhiteboardCleanedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_WHITEBOARD_CLOSED:
                            EventHandler WhiteboardClosedHandler = this.WhiteboardClosed;
                            if (null != WhiteboardClosedHandler)
                            {
                                WhiteboardClosedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_SET_DRAW_POINTER:
                            EventHandler DrawPointerMovedHandler = this.DrawPointerMoved;
                            if (null != DrawPointerMovedHandler)
                            {
                                DrawPointerMovedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_RESET_DRAW_POINTER:
                            EventHandler DrawPointerResetHandler = this.DrawPointerReset;
                            if (null != DrawPointerResetHandler)
                            {
                                DrawPointerResetHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_PARAMETERS_LIST:
                            EventHandler ParameterListReceivedHandler = this.ParameterListReceived;
                            if (null != ParameterListReceivedHandler)
                            {
                                ParameterListReceivedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_DIRECTORY_LIST:
                            EventHandler DirectoryListReceivedHandler = this.DirectoryListReceived;
                            if (null != DirectoryListReceivedHandler)
                            {
                                DirectoryListReceivedHandler(this, e);
                            }
                            break;

                        case JADA.Event.EVT_PING_REPLY:
                            EventHandler PingReplyHandler = this.PingReply;
                            if (null != PingReplyHandler)
                            {
                                PingReplyHandler(this, e);
                            }
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        JADA.Common.LogMessage(String.Format("HandleEventThread {0}\n{1}", e.Message, e.StackTrace));
                        // MessageBox.Show("Errore nell'applicazione: i dettagli sono stati salvati nel file di log", "AREAS Customer Assistant");
                    }
                    finally
                    {
                        if (evtSelf != null)
                        {
                            evtSelf.Dispose();
                        }
                    }
                }
            }
        }