public void FireRepeatedly(TimeSpan period, object State, Func <object, Task> action, string id, string description = "") { State = State ?? new object(); _timers.AddOrUpdate(id, _ => { Logger.Debug("Registering new periodic timer with id {0} to run every {1} seconds. Description: {2}", id, period.TotalSeconds, description); var timer = new Timed { Id = id, Description = description, Expires = DateTime.UtcNow, State = State, Action = action, Lock = new object() }; timer.Timer = new Timer((state) => { var t = (Timed)state; Logger.Debug("Periodic timer id {0} firing. Description: {1}", t.Id, t.Description); if (!Monitor.TryEnter(t.Lock, period)) { Logger.Warn("Failed to run periodic timer id {0} Description: {1} - could not aquire lock on state. This could be due to the timer action taking too long", t.Id, t.Description); return; } try { Task.Run(async() => { await t.Action(t.State).ConfigureAwait(false); }).Wait(); } catch (AggregateException e) { Logger.Error("Periodic timer id {0} threw an exception\nDescription: {1}\nException: {2}", t.Id, t.Description, e); } finally { Monitor.Exit(t.Lock); } }, timer, 0, Convert.ToInt64(period.TotalMilliseconds)); return(timer); }, (_, timer) => { Logger.Debug("Updating existing periodic timer with id {0} to run every {1} seconds. Description: {2}", id, period.TotalSeconds, description); timer.Action = action; // Lock the state incase the timer is currently executing, we shouldn't change the state mid-timer fire lock (timer.State) { timer.State = State; } timer.Description = description; return(timer); }); }
public void Fire(TimeSpan at, object State, Func <object, Task> action, string id, string description = "") { State = State ?? new object(); _timers.AddOrUpdate(id, _ => { Logger.Debug("Registering new timer with id {0} to run in {1} seconds. Description: {2}", id, at.TotalSeconds, description); var timer = new Timed { Id = id, Description = description, Expires = DateTime.UtcNow.Add(at), State = State, Action = action, Lock = new object() }; timer.Timer = new Timer((state) => { var t = (Timed)state; Logger.Debug("Timer id {0} firing", t.Id); Timed placeholder; _timers.TryRemove(t.Id, out placeholder); if (!Monitor.TryEnter(t.Lock, TimeSpan.FromSeconds(10))) { Logger.Warn("Failed to run timer id {0} Description: {1} - could not aquire lock on state", t.Id, t.Description); return; } try { Task.Run(async() => { await t.Action(t.State).ConfigureAwait(false); }).Wait(); } catch (AggregateException e) { Logger.Error("Timer id {0} threw an exception\nDescription: {1}\nException: {2}", t.Id, t.Description, e); } finally { Monitor.Exit(t.Lock); } }, timer, Convert.ToInt64(at.TotalMilliseconds), Timeout.Infinite); return(timer); }, (_, timer) => { Logger.Debug("Updating existing timer with id {0} to run in {1} seconds. Description: {2}", id, at.TotalSeconds, description); timer.Action = action; timer.State = State; timer.Description = description; return(timer); }); }
public static void Execute(int seconds,Timed method) { var lastExecution = DateTime.Now; method(); while (true) { if ((DateTime.Now - lastExecution).TotalSeconds >= seconds) { method(); lastExecution = DateTime.Now; } } }
// Func<T> instead of Action public static Timed <T> Measure(Func <T> func) { if (func == null) { throw new ArgumentNullException(); } var stopWatch = Stopwatch.StartNew(); var result = func(); stopWatch.Stop(); return(Timed.Create(result, stopWatch.Elapsed)); }
public void SqlStringBuildersShouldBeEqual() { SQLiteDatabase db = new SQLiteDatabase($".\\{nameof(SqlStringBuildersShouldBeEqual)}", nameof(SqlStringBuildersShouldBeEqual)); string name = 8.RandomLetters(); TimeSpan elapsed = Timed.Execution(() => { SqlStringBuilder one = TestTableQuery.Where(c => c.Name == name).ToSqlStringBuilder(db); SqlStringBuilder two = TestTableQuery.Where(c => c.Name == name).ToSqlStringBuilder(db); SqlStringBuilder three = TestTableQuery.Where(c => c.Name == "something else").ToSqlStringBuilder(db); Expect.IsTrue(one.EqualTo(two, db)); Expect.IsFalse(one.EqualTo(three, db)); }); OutLineFormat("Operation took: {0}", elapsed.ToString()); }
public void ApplicationRegistryRepositoryGetOneUserShouldHaveNoOrganization() { TimeSpan elapsed = Timed.Execution(() => { ApplicationRegistrationRepository repo = new ApplicationRegistrationRepository(); repo.Database = new SQLiteDatabase($"{nameof(ApplicationRegistryRepositoryGetOneUserShouldHaveNoOrganization)}", nameof(ApplicationRegistryRepositoryGetOneUserShouldHaveNoOrganization)); var user = repo.GetOneUserWhere(c => c.UserName == "bryan"); Expect.IsNotNull(user); Expect.AreEqual(0, user.Organizations.Count); Expect.IsGreaterThan(user.Id, 0); OutLine(user.PropertiesToString(), ConsoleColor.Cyan); repo.Delete(user); user = repo.Retrieve <ApplicationRegistration.User>(user.Id); Expect.IsNull(user); }); OutLine(elapsed.ToString(), ConsoleColor.Cyan); }
// Use this for initialization void Start() { gameObject.SetActive(false); instance = gameObject.GetComponent <Message> (); text = gameObject.GetComponent <Text> (); messageDelayBeforeDisappear = gameObject.GetComponent <Timed> (); GameState.Instance.characterSet += (id) => { if (id == GlobalGameConstants.NULL_ID) { messageDelayBeforeDisappear.Set(2); messageDelayBeforeDisappear.Done += () => { gameObject.SetActive(false); text.text = ""; }; messageDelayBeforeDisappear.On(); } }; GameState.Instance.messageSet += () => { string newMessage = GameState.Instance.MessageState.message; text.text = newMessage; gameObject.SetActive(newMessage.Length > 0); }; }
void Start() { gameObject.SetActive(false); image = gameObject.GetComponent <Image> (); imageDelayBeforeDisappear = gameObject.GetComponent <Timed> (); //register delegate to fetch the image data of character when the new character is set GameState.Instance.characterSet += (id) => { if (id == GlobalGameConstants.NULL_ID) { imageDelayBeforeDisappear.Set(2); imageDelayBeforeDisappear.Done += () => { gameObject.SetActive(false); image.sprite = null; }; imageDelayBeforeDisappear.On(); } else { gameObject.SetActive(true); currentSourceDirectory = $"{CHARACTER_IMAGE_DIRECTORY}/{id}"; image.sprite = Resources.Load <Sprite>($"{currentSourceDirectory}/default"); } }; }
public object Any(Timed request) { Thread.Sleep(request.Milliseconds); return(true); }
/// <summary>Anies the given request.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(Timed request) { Thread.Sleep(request.Milliseconds); return true; }
static string FormatTimedException(Timed <Exception> e) { return(string.Format(@"{0}: {1}", e.Time, e.Value)); }
static async Task Main(string[] args) { var timedString = new Timed <string>("Hello World!", DateTime.Now.AddSeconds(15)); var stoppingTokenSource = new CancellationTokenSource(); timedString.OnExpiration += (timedObject) => { stoppingTokenSource.Cancel(); }; await Task.Delay(TimeSpan.FromMinutes(15), stoppingTokenSource.Token); stoppingTokenSource.Dispose(); Console.WriteLine("Timer has expired."); //var id = "a67e45343c4c49f1a59c3a8ae8e32ffb"; //var secret = "OfREp95eHBg7SF1J8M9QZSx1vojwUSfS"; //var tokenBaseUrl = "https://us.battle.net"; //var apiBaseUrl = "https://us.api.blizzard.com"; //var wowheadUrl = "https://wowhead.com"; //using var httpClient = new HttpClient(); //var authService = new AuthService(httpClient, tokenBaseUrl, id, secret); //var tokenHandler = new TokenHandler(authService); //var token = await tokenHandler.GetAccessTokenAsync(); //var auctionHouseService = new AuctionHouseService(httpClient, tokenHandler, apiBaseUrl); //var realm = new Realm //{ // Name = "Area 52", // Slug = "area-52" //}; //var snapshot = await auctionHouseService.GetSnapshotAsync(realm); //var iconFactory = new IconFactory(); //var wowheadService = new WowheadService(httpClient, iconFactory, "https://wowhead.com"); //var client = new MongoClient(new MongoClientSettings //{ // Server = new MongoServerAddress("192.168.0.103") //}); //var wowDb = client.GetDatabase("wow"); //var collection = wowDb.GetCollection<WowItem>("items"); ////var indexOptions = new CreateIndexOptions(); ////var indexKeys = Builders<WowItem>.IndexKeys.Text(i => i.Name); ////var indexModel = new CreateIndexModel<WowItem>(indexKeys, indexOptions); ////await collection.Indexes.CreateOneAsync(indexModel); //var foundItems = collection.AsQueryable().Where(i => i.Name.Contains("bar", StringComparison.OrdinalIgnoreCase)); //collection.AsQueryable().WhereText("Bar").ToList(); ////var filterBuilder = Builders<WowItem>.Filter; ////var filter = filterBuilder.Text("Arcanite"); ////var foundItems = await collection.Find(filter).ToListAsync(); //foreach (var x in foundItems) //{ // Console.WriteLine($"{x.Id}: {x.Name}"); // Console.WriteLine(); //} //var repo = new ItemRepository("192.168.0.103"); //var allItems = (await repo.GetItemsAsync(0, 500000)).Where(i => i.Name != NullWowItem.NullItemName).ToList(); //var allThatExist = allItems.Where(i => i.Name != NullWowItem.NullItemName || i.Name.StartsWith("OLD", StringComparison.OrdinalIgnoreCase) || i.Name.StartsWith("Test", StringComparison.OrdinalIgnoreCase)).ToList(); //var updatedItems = new List<WowItem>(); //var threadCount = 12; //var ranges = NumberToRanges(allItems.Count(), threadCount); //var httpClients = new List<HttpClient>(); //var services = new List<IWowheadService>(); //var tasks = new List<Task>(); //for (var i = 0; i < threadCount; i++) //{ // //httpClients.Add(new HttpClient()); // //services.Add(new WowheadService(httpClients[i], iconFactory, wowheadUrl)); // var client = new HttpClient(); // var service = new WowheadService(client, iconFactory, wowheadUrl); // var range = ranges[i]; // tasks.Add(Task.Run(async () => // { // var _httpClient = httpClient; // var _service = service; // var _range = range; // for (var i = _range.StartAt; i < _range.EndAt; i++) // { // var item = await _service.GetItemAsync(i); // await repo.AddItemAsync(item); // } // _httpClient.Dispose(); // })); //} //await Task.WhenAll(tasks); //repo.AddItemsAsync(updatedItems); //Parallel.ForEach(allItems, new ParallelOptions { MaxDegreeOfParallelism = 10 }, async item => //{ // var updatedItem = await wowheadService.GetItemAsync(item.Id); // updatedItems.Add(updatedItem); //}); //await repo.AddItemsAsync(updatedItems); //foreach (var item in allThatExist) //{ // Console.WriteLine($"{item.Id}: {item.Name}"); //} //var clothIds = new[] { 4306, 21877, 33470, 4338, 53010, 2592, 2589, 72988 }; ////var clothItems = await repo.GetItemsAsync(new[] { 4306, 21877, 33470, 4338, 53010, 2592, 2589, 72988 }); //var items = new List<WowItem>(); //foreach (var itemId in clothIds) //{ // items.Add(await wowheadService.GetItemAsync(itemId)); //} //await repo.AddItemsAsync(items); //var ids = await repo.GetItemsAsync(clothIds); //var populator = new WowItemPopulator(wowheadService, repo); //await populator.PopulateAsync(); //await repo.AddItemAsync(item); ////var item = await repo.GetItemAsync(12360); //var items = (await repo.GetItemsByFTSAsync("Arcanite")).ToList(); ////Console.WriteLine(item.Name); //foreach (var i in items) //{ // Console.WriteLine($"{i.Id}: {i.Name}"); //} //var count = 30; //var httpClients = new List<HttpClient>(); //var services = new List<WowheadService>(); //for (var i = 0; i < count; i++) //{ // var httpClient = new HttpClient(); // httpClients.Add(httpClient); // services.Add(new WowheadService(httpClient, wowheadUrl)); //} //var populator = new ParallelWowItemPopulator(services.ToArray(), repo); //await populator.PopulateAsync(); //for (var i = 0; i < count; i++) //{ // httpClients[i].Dispose(); //} }
static string FormatTimedException(Timed<Exception> e) { return string.Format(@"{0}: {1}", e.Time, e.Value); }