public virtual DateTime DeadTime(int attempts, TimeSpan? timeoutFactor, TimeSpan? maxDeadTimeout) { var timeout = timeoutFactor.GetValueOrDefault(DefaultTimeout); var maxTimeout = maxDeadTimeout.GetValueOrDefault(MaximumTimeout); var milliSeconds = Math.Min(timeout.TotalMilliseconds * 2 * Math.Pow(2, attempts * 0.5 - 1), maxTimeout.TotalMilliseconds); return Now().AddMilliseconds(milliSeconds); }
public TestBarrier(TestKitBase testKit, int count, TimeSpan? defaultTimeout=null) { _testKit = testKit; _count = count; _defaultTimeout = defaultTimeout.GetValueOrDefault(testKit.TestKitSettings.DefaultTimeout); _barrier = new Barrier(count); }
public OACommandExecuted(DateTime startTime, TimeSpan? duration, string eventName, string subEventText) { this.id = Guid.NewGuid(); this.EventName = eventName; this.StartTime = startTime; this.Duration = duration.GetValueOrDefault(); this.EventCategory = new TimelineCategoryItem("OpenAccess ORM", "#FF0F2B", "#FF0F2B"); this.EventSubText = subEventText; }
public WatchedFileChecker(ReadedFileInfo fileInfo, TimeSpan? delay, CheckMode checkMode) : base(fileInfo) { _delay = delay.GetValueOrDefault(TimeSpan.FromSeconds(5 * 60)); if (_delay <= TimeSpan.FromMilliseconds(1)) throw new ArgumentOutOfRangeException("delay should be greater of 1 ms"); _fileInfo = fileInfo; _checkMode = checkMode; _watcher = createWatch(); Task.Run(() => checkLoop()).ThrowUnhandledException("Error while file checking."); }
public CsvRequestLogger(IVirtualFiles files = null, string requestLogsPattern = null, string errorLogsPattern = null, TimeSpan? appendEvery = null) { this.files = files ?? new FileSystemVirtualPathProvider(HostContext.AppHost, HostContext.Config.WebHostPhysicalPath); this.requestLogsPattern = requestLogsPattern ?? "requestlogs/{year}-{month}/{year}-{month}-{day}.csv"; this.errorLogsPattern = errorLogsPattern ?? "requestlogs/{year}-{month}/{year}-{month}-{day}-errors.csv"; this.appendEverySecs = (int)appendEvery.GetValueOrDefault(TimeSpan.FromSeconds(1)).TotalSeconds; var lastEntry = ReadLastEntry(GetLogFilePath(this.requestLogsPattern, DateTime.UtcNow)); if (lastEntry != null) requestId = lastEntry.Id; timer = new Timer(OnFlush, null, this.appendEverySecs, Timeout.Infinite); }
/// <summary> /// Adds a frame to this animation. /// </summary> /// <param name="img">The image to add</param> /// <param name="x">The positioning x offset this image should be displayed at.</param> /// <param name="y">The positioning y offset this image should be displayed at.</param> public void AddFrame(Image img, int x = 0, int y = 0, TimeSpan? frameDelay = null) { using (var gifStream = new MemoryStream()) { img.Save(gifStream, ImageFormat.Gif); if (_isFirstImage) // Steal the global color table info { InitHeader(gifStream, img.Width, img.Height); } WriteGraphicControlBlock(gifStream, frameDelay.GetValueOrDefault(FrameDelay)); WriteImageBlock(gifStream, !_isFirstImage, x, y, img.Width, img.Height); } _isFirstImage = false; }
/// <summary> /// <para>Await until the given assertion does not throw an exception or the timeout /// expires, whichever comes first. If the timeout expires the last exception /// is thrown.</para> /// <para>The action is called, and if it throws an exception the thread sleeps /// the specified interval before retrying.</para> /// <para>If no timeout is given, take it from the innermost enclosing `within` /// block.</para> /// <para>Note that the timeout is scaled using <see cref="Dilated" />, /// which uses the configuration entry "akka.test.timefactor".</para> /// </summary> /// <param name="assertion">The action.</param> /// <param name="duration">The timeout.</param> /// <param name="interval">The interval to wait between executing the assertion.</param> public void AwaitAssert(Action assertion, TimeSpan? duration=null, TimeSpan? interval=null) { var intervalValue = interval.GetValueOrDefault(TimeSpan.FromMilliseconds(800)); if(intervalValue == Timeout.InfiniteTimeSpan) intervalValue = TimeSpan.MaxValue; intervalValue.EnsureIsPositiveFinite("interval"); var max = RemainingOrDilated(duration); var stop = Now + max; var t = max.Min(intervalValue); while(true) { try { assertion(); return; } catch(Exception) { if(Now + t >= stop) throw; } Thread.Sleep(t); t = (stop - Now).Min(intervalValue); } }
public void Run() { if(this.CurrentItemAmount != this.ItemsToLoad) { int index = 0; int currentIndex = 0; TimeSpan? totalTime = null; TimeSpan totalLoadingTime = new TimeSpan(); foreach(Card card in CardBase.Cards) { foreach(KeyValuePair<Edition, EditionImage> pair in card.EditionPictures) { string filename = Helper.CreateImageFilename(pair.Key.Shortname, pair.Value.Card.Name); if(!File.Exists(filename)) { if(!Directory.Exists("img\\" + pair.Key.Shortname + "\\")) { Directory.CreateDirectory("img\\" + pair.Key.Shortname + "\\"); } TimeSpan loadingTime; Stopwatch watch = Stopwatch.StartNew(); DownloadImage(pair.Value.Url.AbsoluteUri, filename, card.MainType); watch.Stop(); currentIndex++; // calc laoding time loadingTime = watch.Elapsed; totalLoadingTime += loadingTime; // calc total time int imgToLoad = this.ItemsToLoad - this.CurrentItemAmount - currentIndex; long ticks = (totalLoadingTime.Ticks / currentIndex); totalTime = new TimeSpan(ticks * imgToLoad); // raise event if(this.ImageLoaderResponse != null) { this.ImageLoaderResponse(new ImageLoaderEventArgs( pair.Value.Card, pair.Value.Edition, index, totalTime.GetValueOrDefault(), totalLoadingTime )); } } index++; } } } if(this.ImageLoaderFinish != null) { this.ImageLoaderFinish(new ImageLoaderFinishEventArgs("All items successfull loaded!")); } }
private IObservable<Unit> OnStart(TimeSpan? skipAhead) => this.Start(skipAhead.GetValueOrDefault(TimeSpan.Zero));
public TimeSpan GetMillisDuration(string path, TimeSpan? @default = null) { HoconValue value = GetNode(path); if (value == null) return @default.GetValueOrDefault(); return value.GetMillisDuration(); }
/// <summary>Load an <see cref="Asset"/>.</summary> /// <param name="loader"></param> /// <param name="formats"></param> /// <param name="resolveConflict"></param> /// <param name="progress"></param> /// <param name="progressUpdateRate"></param> /// <returns></returns> public static Task<Asset> LoadAssetAsync(AssetLoader loader, IEnumerable<AssetFormat> formats, ResolveLoadConflictCallback resolveConflict = null, AssetLoaderProgressCallback progress = null, TimeSpan? progressUpdateRate = null) { TimeSpan progressUpdateRateValue = progressUpdateRate.GetValueOrDefault(TimeSpan.FromSeconds(0.1)); LoadMatchStrength matchStrength; AssetFormat format = LoadMatchAsset(out matchStrength, loader, formats, resolveConflict); if (loader.Context != null) loader.Context.LoadErrors = loader.Errors; return new Task<Asset>(() => { Asset asset = null; bool complete = false; Thread loadThread = new Thread(() => { asset = format.Load(loader); complete = true; }); loadThread.Start(); while (!complete) { if (!loadThread.IsAlive) throw new InvalidOperationException("The load operation failed."); Thread.Sleep(progressUpdateRateValue); if (progress != null) progress.Invoke(loader); } return asset; }); }
static Func<ErrorContext, RecoverabilityAction> CreatePolicy(int maxImmediateRetries = 2, int maxDelayedRetries = 2, TimeSpan? delayedRetryDelay = null) { var config = new RecoverabilityConfig(new ImmediateConfig(maxImmediateRetries), new DelayedConfig(maxDelayedRetries, delayedRetryDelay.GetValueOrDefault(TimeSpan.FromSeconds(2))), new FailedConfig("errorQueue")); return context => DefaultRecoverabilityPolicy.Invoke(config, context); }
//TODO:: add GSM and GPS status to events. ///// <summary> ///// GSM Strength ///// </summary> //public double? GSMStrength { get; set; } ///// <summary> ///// GPS Connection ///// </summary> //public double? GPSConnection { get; set; } ///// <summary> ///// GPS Lost Time ///// </summary> //public double? GPSLostTime { get; set; } ///// <summary> ///// GPS State ///// </summary> //public GpsState? GpsState { get; set; } public override bool RepresentsRecentChange(TimeSpan? timeWindow) { return ((TimeSpan)(DateTime.UtcNow - Time)).TotalSeconds < timeWindow.GetValueOrDefault().TotalSeconds; }
/// <summary> /// Shuts down the specified system. /// On failure debug output will be logged about the remaining actors in the system. /// If verifySystemShutdown is true, then an exception will be thrown on failure. /// </summary> /// <param name="system">The system to shutdown.</param> /// <param name="duration">The duration to wait for shutdown. Default is 5 seconds multiplied with the config value "akka.test.timefactor"</param> /// <param name="verifySystemShutdown">if set to <c>true</c> an exception will be thrown on failure.</param> protected virtual void Shutdown(ActorSystem system, TimeSpan? duration = null, bool verifySystemShutdown = false) { if (system == null) system = _testState.System; var durationValue = duration.GetValueOrDefault(Dilated(TimeSpan.FromSeconds(5)).Min(TimeSpan.FromSeconds(10))); var wasShutdownDuringWait = system.Terminate().Wait(durationValue); if(!wasShutdownDuringWait) { const string msg = "Failed to stop [{0}] within [{1}] \n{2}"; if(verifySystemShutdown) throw new TimeoutException(string.Format(msg, system.Name, durationValue, "")); //TODO: replace "" with system.PrintTree() system.Log.Warning(msg, system.Name, durationValue, ""); //TODO: replace "" with system.PrintTree() } }
/// <summary> /// Schedules an ad that is to be handled by an AdPayloadHandlerPlugin. /// A valid AdPayloadHandlerPlugin must be part of your application or this will not be handled. /// </summary> /// <param name="adTrigger">An object containing information about the ad source and target</param> /// <param name="startTime">The position within the media where this ad should be played. If ommited ad will begin playing immediately.</param> /// <returns>An object that contains information about the scheduled ad.</returns> public ScheduledAd ScheduleAdTrigger(IAdSequencingTrigger adTrigger, TimeSpan? startTime = null) { var adStartTime = startTime.GetValueOrDefault(RelativeMediaPluginPosition); var result = new ScheduledAd(adTrigger); var adMarker = new AdMarker() { Immediate = !startTime.HasValue, Begin = adStartTime, Id = Guid.NewGuid().ToString(), ScheduledAd = result, End = adStartTime.Add(adTrigger.Duration.GetValueOrDefault(TimeSpan.FromDays(1))) // update the end based on the duration }; // Immediate == true will trigger the timeline marker immediately instead of waiting for polling to occur if (adMarker.Immediate) { var duration = adMarker.Duration; adMarker.Begin = RelativeMediaPluginPosition; adMarker.End = adMarker.Begin.Add(duration); // update the end based on the duration AdMarkers.Add(adMarker); // force a check on the postions, we know there is one that needs to be fired if (!isSeekActive) _adMarkerManager.CheckMarkerPositions(RelativeMediaPluginPosition, AdMarkers, seekInProgress); } else { AdMarkers.Add(adMarker); } return result; }
/// <summary> /// Schedules an ad that is to be handled by an AdPayloadHandlerPlugin. /// A valid AdPayloadHandlerPlugin must be part of your application or this will not be handled. /// </summary> /// <param name="adSource">The Uri of Ad's source. Often a VAST document</param> /// <param name="format">The format of the ad source. e.g. "vast"</param> /// <param name="startTime">The position within the media where this ad should be played. If ommited ad will begin playing immediately.</param> /// <param name="duration">The duration of the ad content that should be played. If ommitted the plugin will play the full duration of the ad content.</param> /// <returns>An object that contains information about the scheduled ad.</returns> public ScheduledAd ScheduleAdTrigger(string adSource, string format = "vast", TimeSpan? startTime = null, TimeSpan? duration = null) { var adSequencingSource = new AdSequencingSource(); adSequencingSource.Format = format; adSequencingSource.Uri = adSource; var adTrigger = new AdSequencingTrigger(); adTrigger.Duration = duration.GetValueOrDefault(TimeSpan.FromDays(1)); adTrigger.Sources.Add(adSequencingSource); return ScheduleAdTrigger(adTrigger, startTime); }
/// <summary> /// <para>Await until the given condition evaluates to <c>true</c> or the timeout /// expires, whichever comes first.</para> /// <para>If no timeout is given, take it from the innermost enclosing `within` /// block (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor /// specified in config value "akka.test.timefactor"..</para> /// <para>A call to <paramref name="conditionIsFulfilled"/> is done immediately, then the threads sleep /// for about a tenth of the timeout value, before it checks the condition again. This is repeated until /// timeout or the condition evaluates to <c>true</c>. To specify another interval, use the overload /// <see cref="AwaitCondition(System.Func{bool},System.Nullable{System.TimeSpan},System.Nullable{System.TimeSpan},string)"/> /// </para> /// </summary> /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param> /// <param name="max">The maximum duration. If undefined, uses the remaining time /// (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor /// specified in config value "akka.test.timefactor".</param> /// <param name="message">The message used if the timeout expires.</param> public void AwaitCondition(Func<bool> conditionIsFulfilled, TimeSpan? max, string message = null) { var maxDur = RemainingOrDilated(max); var interval = new TimeSpan(max.GetValueOrDefault().Ticks / 10); InternalAwaitCondition(conditionIsFulfilled, maxDur, interval, message, (format, args) => _assertions.Fail(format, args)); }
private static void ConfigureDispatcher(this FluentConfig self, string type, int throughput, TimeSpan? throughputDeadlineTimeout) { self.AsInstanceOf<FluentConfigInternals>() .AppendLine(string.Format("akka.actor.default-dispatcher.type = '{0}'", type)); self.AsInstanceOf<FluentConfigInternals>() .AppendLine(string.Format("akka.actor.default-dispatcher.throughput = {0}", throughput)); self.AsInstanceOf<FluentConfigInternals>() .AppendLine(string.Format("akka.actor.default-dispatcher.throughput-deadline-time = {0}ms", throughputDeadlineTimeout.GetValueOrDefault(TimeSpan.FromSeconds(0)).TotalMilliseconds)); }
public TimeoutActor(TestLatch timeoutLatch, TimeSpan? timeout) { _timeoutLatch = timeoutLatch; Context.SetReceiveTimeout(timeout.GetValueOrDefault()); }
private TestResult FinishStep(TestOutcome outcome, TimeSpan? actualDuration, bool isDisposing) { EventHandler cachedFinishingHandlers; lock (syncRoot) { if (! IsRunning) { if (isDisposing) return result ?? new TestResult(TestOutcome.Error); throw new InvalidOperationException("Cannot finish a step unless the test step is running."); } this.outcome = outcome; executionStatus = StatusFinishing; LifecyclePhase = LifecyclePhases.Finishing; cachedFinishingHandlers = finishingHandlers; finishingHandlers = null; } // Note: We no longer need to hold the lock because none of the state used from here on can change // since the status is now StatusFinishing. try { if (parent != null) parent.Finishing -= HandleParentFinishedBeforeThisContext; using (Enter()) EventHandlerPolicy.SafeInvoke(cachedFinishingHandlers, this, EventArgs.Empty); if (isDisposing) logWriter.Failures.Write("The test step was orphaned by the test runner!\n"); logWriter.Close(); result = new TestResult(outcome) { AssertCount = assertCount, Duration = actualDuration.GetValueOrDefault(stopwatch.Elapsed) }; MessageSink.Publish(new TestStepFinishedMessage() { StepId = testStep.Id, Result = result }); if (contextCookie != null) { if (!isDisposing) contextCookie.Dispose(); contextCookie = null; } return result; } catch (Exception ex) { UnhandledExceptionPolicy.Report("An unhandled exception occurred while finishing a test step.", ex); return new TestResult(TestOutcome.Error); } finally { lock (syncRoot) executionStatus = StatusFinished; } }
private PageRequest ProcessEvent(Guid siteId, Uri urlReferrer, Guid? requestId = null, TimeSpan? duration = null, string refferer = "") { Guid sessionId = Guid.Empty; var sessionCookie = Request.Cookies["SkynerSessionId"]; if (sessionCookie != null) Guid.TryParse(sessionCookie.Value, out sessionId); if (sessionId == null || sessionId.Equals(Guid.Empty)) sessionId = Guid.NewGuid(); var httpCookie = new HttpCookie("SkynerSessionId"); httpCookie.Domain = Request.Url.Host; httpCookie.Value = sessionId.ToString(); httpCookie.HttpOnly = true; Response.SetCookie(httpCookie); var request = new PageRequest { Id = requestId.GetValueOrDefault(Guid.NewGuid()), SessionIdentifier = sessionId, Url = urlReferrer.AbsolutePath, Domain = urlReferrer.Host, IpAddress = Request.UserHostAddress, Browser = (byte)Request.Browser.Browser.GetBrowserFromString(), Duration = duration.GetValueOrDefault(TimeSpan.Zero), Refferer = refferer, SiteId = siteId }; try { SendEvent(request); } catch { throw new HttpException(404, "not found"); } return request; }
/// <summary> /// If <paramref name="timeout"/> is defined it is returned; otherwise /// the config value "akka.test.single-expect-default" is returned. /// </summary> public TimeSpan GetTimeoutOrDefault(TimeSpan? timeout) { return timeout.GetValueOrDefault(SingleExpectDefaultTimeout); }
/// <summary> /// Writes a <see cref="Nullable{TimeSpan}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param> public virtual void WriteValue(TimeSpan? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } }
/// <summary> /// Retrieves a <see cref="TimeSpan"/> value from the specified path in the configuration. /// </summary> /// <param name="path">The path that contains the value to retrieve.</param> /// <param name="default">The default value to return if the value doesn't exist.</param> /// <param name="allowInfinite"><c>true</c> if infinite timespans are allowed; otherwise <c>false</c>.</param> /// <returns>The <see cref="TimeSpan"/> value defined in the specified path.</returns> public virtual TimeSpan GetTimeSpan(string path, TimeSpan? @default = null, bool allowInfinite = true) { HoconValue value = GetNode(path); if (value == null) return @default.GetValueOrDefault(); return value.GetTimeSpan(allowInfinite); }
/// <summary> /// Applies the fault handling `Directive` (Resume, Restart, Stop) specified in the `Decider` /// to all children when one fails, as opposed to <see cref="AllForOneStrategy" /> that applies /// it only to the child actor that failed. /// </summary> /// <param name="maxNrOfRetries"> /// the number of times a child actor is allowed to be restarted, negative value and null means no limit, /// if the limit is exceeded the child actor is stopped. /// </param> /// <param name="withinTimeRange">duration of the time window for maxNrOfRetries, <see cref="Timeout.InfiniteTimeSpan"/> means no window.</param> /// <param name="decider">mapping from Exception to <see cref="Directive"/></param> public AllForOneStrategy(int? maxNrOfRetries, TimeSpan? withinTimeRange, Func<Exception, Directive> decider) : this(maxNrOfRetries.GetValueOrDefault(-1), withinTimeRange.GetValueOrDefault(Timeout.InfiniteTimeSpan).Milliseconds, decider) { //Intentionally left blank }
/// <summary> /// <para>Await until the given condition evaluates to <c>true</c> or the timeout /// expires, whichever comes first. Returns <c>true</c> if the condition was fulfilled.</para> /// <para>The parameter <paramref name="interval"/> specifies the time between calls to <paramref name="conditionIsFulfilled"/> /// Between calls the thread sleeps. If <paramref name="interval"/> is not specified or <c>null</c> 100 ms is used.</para> /// </summary> /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param> /// <param name="max">The maximum duration.</param> /// <param name="interval">Optional. The time between calls to <paramref name="conditionIsFulfilled"/> to check /// if the condition is fulfilled. Between calls the thread sleeps. If undefined, 100 ms is used /// </param> public bool AwaitConditionNoThrow(Func<bool> conditionIsFulfilled, TimeSpan max, TimeSpan? interval = null) { var intervalDur = interval.GetValueOrDefault(TimeSpan.FromMilliseconds(100)); return InternalAwaitCondition(conditionIsFulfilled, max, intervalDur, (f, a) => { }); }
public void StartLockTimer(TimeSpan? initalTimeSpan = null) { ActivityChecker.PauseForLockTimer(initalTimeSpan); if (!runningTimerWhenIdle.HasValue) { runningTimerWhenIdle = JiraTimerCollection.GetRunningTimerId(); if (runningTimerWhenIdle.HasValue) { jiraTimerCollection.StopTimer(runningTimerWhenIdle.Value, true); if (initalTimeSpan.HasValue) { jiraTimerCollection.AdjustTime(runningTimerWhenIdle.Value, initalTimeSpan.Value.Hours, initalTimeSpan.Value.Minutes, false); } } } idleTimerCollection.NewLockTimer(initalTimeSpan.GetValueOrDefault(new TimeSpan())); }