Exemplo n.º 1
0
 void InitTimer()
 {
     if (Timer == null)
     {
         Timer = new TaskTimer(50, Fire, 500);
     }
 }
Exemplo n.º 2
0
        public MainForm()
        {
            // 各メンバ変数の初期化
            InitializeComponent();
            m_stopwatch                 = new Stopwatch();
            m_filePath                  = "TaskTimeRecord.csv";
            m_encoding                  = System.Text.Encoding.GetEncoding("UTF-8");
            m_noticeTimeSpanRunning     = new TimeSpan(0, 10, 0);
            m_noticeTimeSpanStopping    = new TimeSpan(0, 10, 0);
            m_nextNoticeTimeSpanRunning = TimeSpan.Zero.Add(m_noticeTimeSpanRunning);
            m_prevNoticeTimeStopping    = DateTime.Now;

            // メッセージラベルのサイズを親コンポーネントに合わせる
            Message_Label.Width  = Message_TableLayoutPanel.Width;
            Message_Label.Height = Message_TableLayoutPanel.Height;

            // メッセージリセット
            ResetMessage();

            // タスク名コンボボックスのリスト初期化
            RenewTaskComboBoxList();

            // タスク情報表示の初期化
            DisplayDefaultTaskInfo();

            // トースト通知機能設定の初期化
            InitialSettingToastNotification();

            // タイマースタート
            TaskTimer.Start();
        }
 protected TelemetryBuffer()
 {
     this.flushTimer = new TaskTimer {
         Delay = DefaultFlushDelay
     };
     this.transmissionBuffer = new List <ITelemetry>(this.Capacity);
 }
Exemplo n.º 4
0
        //--- Constructors ---
        public SearchInstanceData(string indexPath, Analyzer analyzer, UpdateDelayQueue queue, TimeSpan commitInterval, TaskTimerFactory taskTimerFactory)
        {
            _analyzer  = analyzer;
            _directory = FSDirectory.GetDirectory(indexPath);

            // Note (arnec): Needed with SimpleFSLock, since a hard shutdown will have left the lock dangling
            IndexWriter.Unlock(_directory);
            try {
                _writer = new IndexWriter(_directory, _analyzer, IndexWriter.MaxFieldLength.UNLIMITED);
            } catch (CorruptIndexException e) {
                _log.WarnFormat("The Search index at {0} is corrupt. You must repair or delete it before restarting the service. If you delete it, you must rebuild your index after service restart.", indexPath);
                if (e.Message.StartsWith("Unknown format version"))
                {
                    _log.Warn("The index is considered corrupt because it's an unknown version. Did you accidentally downgrade your install?");
                }
                throw;
            }
            _reader           = IndexReader.Open(_directory);
            _searcher         = new IndexSearcher(_reader);
            _queue            = queue;
            _commitInterval   = commitInterval;
            _taskTimerFactory = taskTimerFactory;
            if (_commitInterval != TimeSpan.Zero)
            {
                _commitTimer = _taskTimerFactory.New(_commitInterval, Commit, null, TaskEnv.None);
            }
        }
 public SessionValidationWorker(ILogger logger, GameSessions gameSessions)
 {
     _logger       = logger;
     _gameSessions = gameSessions;
     _backgroundSessionsCheckerTimer = new TaskTimer(TimeSpan.FromSeconds(SessionsCheckIntervalInSeconds), PerformSessionsCheckTask);
     Name = "Session Validation Worker";
 }
Exemplo n.º 6
0
 public ElmaTaskProvider(IElmaServiceProvider elmaServiceProvider, IElmaUser user, TaskTimer timer)
 {
     _wcfService  = elmaServiceProvider.ElmaWcfService;
     _user        = user;
     _timer       = timer;
     UpdateNeeded = true;
 }
Exemplo n.º 7
0
        private async Task DoUpdate()
        {
            //update must wait for any inserts to complete (to avoid updates on records that haven't been inserted yet)
            if (_createRecordsTask != null)
            {
                var result = await _createRecordsTask;
                WriteDataTicks += result;
            }

            if (_updateRecordsTask != null)
            {
                var result = await _updateRecordsTask;
                WriteDataTicks += result;
            }

            var updateQueries = new List <UpdateQuery>();

            foreach (var row in _updateRows)
            {
                var updateQuery = new UpdateQuery(
                    _targetTable.Name,
                    _targetTable.Columns.Where(c => c.DeltaType != TableColumn.EDeltaType.SurrogateKey).Select(c => new QueryColumn(c, row[_targetTable.GetOrdinal(c.Name)])).ToList(),
                    _targetTable.Columns.Where(c => c.DeltaType == TableColumn.EDeltaType.SurrogateKey).Select(c => new Filter(c, Filter.ECompare.IsEqual, row[_targetTable.GetOrdinal(c.Name)])).ToList()
                    );

                updateQueries.Add(updateQuery);
            }

            _updateRecordsTask = TaskTimer.Start(() => _targetConnection.ExecuteUpdate(_targetTable, updateQueries, _cancellationToken));              //this has no await to ensure processing continues.

            _updateRows = new TableCache();
        }
Exemplo n.º 8
0
        private XDoc FetchSchema(Plug adoNetPlug)
        {
            XDoc   ret = null;
            string key = adoNetPlug.At(METADATA_PATH).ToString();

            lock (_cache) {
                _cache.TryGetValue(key, out ret);
            }

            if (ret == null)
            {
                string temp = adoNetPlug.At(METADATA_PATH).Get().AsTextReader().ReadToEnd();

                //HACKHACKHACK to workaround ns issue
                temp = temp.Replace("xmlns=\"http://schemas.microsoft.com/ado/2006/04/edm\"", "");
                ret  = XDocFactory.From(temp, MimeType.XML);

                // add result to cache and start a clean-up timer
                lock (_cache) {
                    _cache[key] = ret;
                }

                TaskTimer.New(TimeSpan.FromSeconds(CACHE_TTL), RemoveCachedEntry, key, TaskEnv.None);
            }

            //TODO: throw exception if schema is invalid somehow (or if the schema changed)
            return(ret);
        }
Exemplo n.º 9
0
 public UpdateHelper(FollowContext followContext, SourceManager sourceManager, FollowHelper followHelper, TaskTimer taskTimer)
 {
     _followContext = followContext;
     _sourceManager = sourceManager;
     _followHelper  = followHelper;
     _taskTimer     = taskTimer;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Create a new timer and set its fire time.
        /// </summary>
        /// <param name="when">Relateive time from now until when the timer should fire.</param>
        /// <param name="handler">The action to invoke when the timer fires.</param>
        /// <param name="state">A state object to associate with the timer.</param>
        /// <param name="env">The environment in which the timer should fire.</param>
        /// <returns>New timer instance.</returns>
        public TaskTimer New(TimeSpan when, Action <TaskTimer> handler, object state, TaskEnv env)
        {
            var result = new TaskTimer(this, handler, state);

            result.Change(when, env);
            return(result);
        }
Exemplo n.º 11
0
        protected void OnInstanceExpireTimer(TaskTimer timer)
        {
            var wikiId = (string)timer.State;

            _log.DebugFormat("instance '{0}' expired", wikiId);
            OutOfContextShutdown(wikiId);
        }
 //--- Constructors ---
 internal InMemoryKeyValueCache(ISerializer serializer, int maxSize, TaskTimerFactory timerFactory)
 {
     _serializer = serializer;
     _maxSize    = maxSize;
     _flushTimer = timerFactory.New(TimeSpan.FromSeconds(1), Flush, null, TaskEnv.None);
     _cache      = new ExpiringDictionary <string, Entry>(timerFactory);
 }
Exemplo n.º 13
0
 protected virtual void EnableUpdates()
 {
     if (_taskTimer == null)
     {
         _taskTimer = new TaskTimer(Refresh, null, 0, 1000, true);
     }
 }
Exemplo n.º 14
0
            protected override void OnTick()
            {
                TaskTimer thisTimer = new TaskTimer(i_item);

                thisTimer.Start();
                RunThis(true);
            }
Exemplo n.º 15
0
        public void TaskTimer_Shutdown()
        {
            var shouldFire = new ManualResetEvent(false);
            var neverFires = new ManualResetEvent(false);

            TaskTimer.New(
                TimeSpan.FromSeconds(2),
                delegate(TaskTimer tt) {
                _log.DebugFormat("this task timer should never have fired");
                neverFires.Set();
            },
                null,
                TaskEnv.None);
            TaskTimer.New(
                TimeSpan.FromSeconds(1),
                delegate(TaskTimer tt) {
                _log.DebugFormat("this task timer should fire before we try shutdown");
                shouldFire.Set();
            },
                null,
                TaskEnv.None);
            _log.DebugFormat("waiting for first task");
            Assert.IsTrue(shouldFire.WaitOne(2000, false));
            _log.DebugFormat("starting shutdown");
            TaskTimer.Shutdown();
            _log.DebugFormat("shutdown complete");
            Assert.IsFalse(neverFires.WaitOne(2000, false));
        }
Exemplo n.º 16
0
 private CacheEntry()
 {
     _memoryExpire = new TaskTimer(delegate(TaskTimer tt) {
         _log.DebugFormat("flushing memory cache for '{0}'", Id);
         Cache = null;
     }, null);
 }
        private static string CachedWebGet(XUri uri, double?ttl, bool?nilIfMissing)
        {
            // fetch message from cache or from the web
            string result;

            lock (_webTextCache) {
                if (_webTextCache.TryGetValue(uri, out result))
                {
                    return(result);
                }
            }

            // do the web request
            Result <DreamMessage> response = new Result <DreamMessage>();

            Plug.New(uri).WithTimeout(DEFAULT_WEB_TIMEOUT).InvokeEx("GET", DreamMessage.Ok(), response);
            DreamMessage message = response.Wait();

            try {
                // check message status
                if (!message.IsSuccessful)
                {
                    if (nilIfMissing.GetValueOrDefault())
                    {
                        return(null);
                    }
                    return(message.Status == DreamStatus.UnableToConnect
                        ? string.Format("(unable to fetch text document from uri [status: {0} ({1}), message: \"{2}\"])", (int)message.Status, message.Status, message.ToDocument()["message"].AsText)
                        : string.Format("(unable to fetch text document from uri [status: {0} ({1})])", (int)message.Status, message.Status));
                }

                // check message size
                Result resMemorize = message.Memorize(InsertTextLimit, new Result()).Block();
                if (resMemorize.HasException)
                {
                    return(nilIfMissing.GetValueOrDefault() ? null : "(text document is too large)");
                }

                // detect encoding and decode response
                var stream   = message.AsStream();
                var encoding = stream.DetectEncoding() ?? message.ContentType.CharSet;
                result = encoding.GetString(stream.ReadBytes(-1));
            } finally {
                message.Close();
            }

            // start timer to clean-up cached result
            lock (_webTextCache) {
                _webTextCache[uri] = result;
            }
            double timeout = Math.Min(60 * 60 * 24, Math.Max(ttl ?? MinCacheTtl, 60));

            TaskEnv.ExecuteNew(() => TaskTimer.New(TimeSpan.FromSeconds(timeout), timer => {
                lock (_webTextCache) {
                    _webTextCache.Remove((XUri)timer.State);
                }
            }, uri, TaskEnv.None));
            return(result);
        }
Exemplo n.º 18
0
        private static Yield ExecuteProcess_Helper(string application, string cmdline, Stream input, Stream output, Stream error, Result <int> result)
        {
            // start process
            var proc = new Process();

            proc.StartInfo.FileName               = application;
            proc.StartInfo.Arguments              = cmdline;
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.CreateNoWindow         = true;
            proc.StartInfo.RedirectStandardInput  = (input != null);
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError  = true;
            proc.Start();

            // inject input
            if (input != null)
            {
                input.CopyTo(proc.StandardInput.BaseStream, long.MaxValue, new Result <long>(TimeSpan.MaxValue)).WhenDone(_ => {
                    // trying closing the original input stream
                    try {
                        input.Close();
                    } catch { }

                    // try closing the process input pipe
                    try {
                        proc.StandardInput.Close();
                    } catch { }
                });
            }

            // extract output stream
            Result <long> outputDone = proc.StandardOutput.BaseStream.CopyTo(output, long.MaxValue, new Result <long>(TimeSpan.MaxValue));

            // extract error stream
            Result <long> errorDone = proc.StandardError.BaseStream.CopyTo(error, long.MaxValue, new Result <long>(TimeSpan.MaxValue));
            TaskTimer     timer     = TaskTimerFactory.Current.New(result.Timeout, delegate(TaskTimer t) {
                try {
                    // NOTE (steveb): we had to add the try..catch handler because mono throws an exception when killing a terminated process (why? who knows!)

                    proc.Kill();
                } catch { }
            }, null, TaskEnv.New());

            // wait for output and error streams to be done
            yield return(new AResult[] { outputDone, errorDone }.Join());

            int?exitCode = WaitForExit(proc, result.Timeout);

            timer.Cancel();
            proc.Close();
            if (exitCode.HasValue)
            {
                result.Return(exitCode.Value);
            }
            else
            {
                result.Throw(new InvalidOperationException("Unable to access process exit code"));
            }
        }
Exemplo n.º 19
0
        private void OnTimeout(TaskTimer timer)
        {
            XUri uri = (XUri)timer.State;

            lock (_feeds) {
                _feeds.Remove(uri);
            }
        }
Exemplo n.º 20
0
    static void Init()
    {
        TaskTimer tt = (TaskTimer)EditorWindow.GetWindow(typeof(TaskTimer));

        tt.Show();

        EditorPrefs.SetString("TaskInProgress", "NA");
    }
Exemplo n.º 21
0
 public RatingCalculationWorker(ILogger logger, GameSessions gameSessions, ILocalNodeRatingDataAccess localNodeRatingDataAccess)
 {
     _logger       = logger;
     _gameSessions = gameSessions;
     _localNodeRatingDataAccess         = localNodeRatingDataAccess;
     _backgroundSaveHistoryCheckerTimer = new TaskTimer(TimeSpan.FromSeconds(TimeSaveInSeconds), PerformRatingCalculation);
     Name = "Rating Calculation Worker";
 }
Exemplo n.º 22
0
 public RatingAggregationWorker(ILogger logger, GameSessions gameSessions, IServerDataAccessService serverDataAccessService)
 {
     _logger                            = logger;
     _gameSessions                      = gameSessions;
     _serverDataAccessService           = serverDataAccessService;
     _backgroundSaveHistoryCheckerTimer = new TaskTimer(TimeSpan.FromSeconds(TimeSaveInSeconds), SaveHistoryCheckTask);
     Name = "Rating Aggregation Worker";
 }
Exemplo n.º 23
0
 public ScheduleTaskInfo(string name, Action <TimeSpan> task, TimeSpan interval)
 {
     this.Name         = name;
     this.Task         = task;
     this.Interval     = interval;
     this._timer       = new TaskTimer();
     this._timer.Tick += this.OnTimerTick;
 }
 //--- Constructors ---
 public NotificationDelayQueue(TimeSpan delay, CoroutineHandler <NotificationUpdateRecord, Result> callback)
 {
     _delay      = delay;
     _callback   = callback;
     _queueTimer = new TaskTimer(CheckExpire, null);
     _queueTimer.Change(_delay, TaskEnv.None);
     _dispatchQueue = new ProcessingQueue <NotificationUpdateRecord>(Dispatch, 10);
 }
Exemplo n.º 25
0
		public TaskManagerDaily () : base( 0x0EDE )
		{
			Movable = false;
			Name = "Task Manager Daily";
			Visible = false;
			TaskTimer thisTimer = new TaskTimer( this ); 
			thisTimer.Start(); 
		}
Exemplo n.º 26
0
 private void OnTimer(TaskTimer timer)
 {
     if (_disposed)
     {
         return;
     }
     RemoveCachedEntry((string)timer.State);
 }
Exemplo n.º 27
0
        private DisasmProject InstantiateProject(string dataPathName,
                                                 out FileLoadReport projectLoadReport)
        {
            DisasmProject project = new DisasmProject();

            // always use AppDomain sandbox

            projectLoadReport = null;

            int testNum = GetTestNum(dataPathName);

            if (testNum < 2000)
            {
                // create new disasm project for data file
                byte[] fileData;
                try {
                    fileData = LoadDataFile(dataPathName);
                } catch (Exception ex) {
                    ReportErrMsg(ex.Message);
                    return(null);
                }

                project.Initialize(fileData.Length);
                project.PrepForNew(fileData, Path.GetFileName(dataPathName));
                // no platform symbols to load
            }
            else
            {
                // deserialize project file, failing if we can't find it
                string projectPathName = dataPathName + ProjectFile.FILENAME_EXT;
                if (!ProjectFile.DeserializeFromFile(projectPathName,
                                                     project, out projectLoadReport))
                {
                    ReportErrMsg(projectLoadReport.Format());
                    return(null);
                }

                byte[] fileData;
                try {
                    fileData = LoadDataFile(dataPathName);
                } catch (Exception ex) {
                    ReportErrMsg(ex.Message);
                    return(null);
                }

                project.SetFileData(fileData, Path.GetFileName(dataPathName));
                project.ProjectPathName = projectPathName;
                project.LoadExternalFiles();
            }

            TaskTimer genTimer = new TaskTimer();
            DebugLog  genLog   = new DebugLog();

            genLog.SetMinPriority(DebugLog.Priority.Silent);
            project.Analyze(UndoableChange.ReanalysisScope.CodeAndData, genLog, genTimer);

            return(project);
        }
Exemplo n.º 28
0
 private void Flush(TaskTimer flushTimer)
 {
     if (_isDisposed)
     {
         return;
     }
     Flush();
     flushTimer.Change(TimeSpan.FromSeconds(1), TaskEnv.None);
 }
Exemplo n.º 29
0
 private void initTaskTimerModel(int totalMiliseconds = Constants.DefaultStartingTimeInMiliseconds, string description = Constants.DefaultTimerDescription)
 {
     taskTimerModel                      = new TaskTimer();
     taskTimerModel.IsComplete           = false;
     taskTimerModel.IsRunning            = false;
     taskTimerModel.RemainingMiliseconds = totalMiliseconds;
     taskTimerModel.TotalMiliseconds     = totalMiliseconds;
     taskTimerModel.Description          = description;
 }
Exemplo n.º 30
0
        public void timer_ElapsedTest()
        {
            TaskTimer target  = new TaskTimer(10);
            bool      elapsed = false;

            target.Action = () => elapsed = true;
            Thread.Sleep(200);
            Assert.IsTrue(elapsed, "TaskTimer didn't elapse");
        }
Exemplo n.º 31
0
 public ThreadTile()
 {
     this.InitializeComponent();
     MainBorder.DataContext = this;
     Shell.IsNarrowViewChanged.AddCallback(this);
     var timerOnClick = CreateTimerOnTick(new WeakReference<ThreadTile>(this));
     this.timer = new TaskTimer(Dispatcher);
     timer.Tick += timerOnClick;
     this.Loaded += OnLoaded;
     this.Unloaded += OnUnloaded;
 }
Exemplo n.º 32
0
 //--- Construtors
 public MemoryPubSubDispatchQueue(string location, TaskTimerFactory taskTimerFactory, TimeSpan retryTime, Func<DispatchItem, Result<bool>> handler)
 {
     if(string.IsNullOrEmpty(location)) {
         throw new ArgumentNullException("location");
     }
     if(taskTimerFactory == null) {
         throw new ArgumentNullException("taskTimerFactory");
     }
     if(handler == null) {
         throw new ArgumentNullException("handler");
     }
     _location = location;
     _retryTime = retryTime;
     _queueTimer = taskTimerFactory.New(RetryDequeue, null);
     _dequeueHandler = handler;
 }
Exemplo n.º 33
0
 //--- Construtors
 public PersistentPubSubDispatchQueue(string queuePath, TaskTimerFactory taskTimerFactory, TimeSpan retryTime, Func<DispatchItem, Result<bool>> handler)
 {
     if(string.IsNullOrEmpty(queuePath)) {
         throw new ArgumentNullException("location");
     }
     if(taskTimerFactory == null) {
         throw new ArgumentNullException("taskTimerFactory");
     }
     if(handler == null) {
         throw new ArgumentNullException("handler");
     }
     _queuePath = queuePath;
     _retryTime = retryTime;
     _queueTimer = taskTimerFactory.New(RetryDequeue, null);
     _queue = new TransactionalQueue<DispatchItem>(new MultiFileQueueStream(queuePath), new DispatchItemSerializer()) {
         DefaultCommitTimeout = TimeSpan.MaxValue
     };
     _dequeueHandler = handler;
     Kick();
 }
        private static TaskTimer InternalCreateAndStartTimer(
            int intervalInMilliseconds,
            Action action)
        {
            var timer = new TaskTimer
            {
                Delay = TimeSpan.FromMilliseconds(intervalInMilliseconds)
            };

            Func<Task> task = null;

            task = () =>
                {
                    timer.Start(task);
                    action();
                    return TaskEx.FromResult<object>(null);
                };

            timer.Start(task);

            return timer;
        }
Exemplo n.º 35
0
 private void AutoDeletePost(TaskTimer timer)
 {
     XAtomFeed feed = _feed;
     if(feed != null) {
         lock(feed) {
             feed[string.Format("_:entry[_:id='{0}']", Self.At(((int)timer.State).ToString()).Uri.AsPublicUri())].Remove();
         }
     }
 }
Exemplo n.º 36
0
        private void OnExpire(TaskTimer timer)
        {
            string name = (string)timer.State;
            lock(_directory) {

                // check if the record still exists
                DirectoryRecord record;
                if(_directory.TryGetValue(name, out record)) {

                    // verify if the record should still be deleted
                    if(record.Expiration <= timer.When) {
                        _directory.Remove(record.Name);
                    } else {
                        timer.Change(record.Expiration, TaskEnv.Clone());
                    }
                }
            }
        }
Exemplo n.º 37
0
 private void RetryDequeue(TaskTimer obj)
 {
     TryDequeue();
 }