Only execute method after X number of seconds since last use

I have a foreach statement, and I need to make sure that the method called at the end of the foreach, and if the instructions are executed only 3 seconds after the last execution time.

Here is the code.

//Go over Array for each id in allItems foreach (int id in allItems) { if (offered > 0 && itemsAdded != (offered * 3) && tDown) { List<Inventory.Item> items = Trade.MyInventory.GetItemsByDefindex(id); foreach (Inventory.Item item in items) { if (!Trade.myOfferedItems.ContainsValue(item.Id)) { //Code to only execute if x seconds have passed since it last executed. if (Trade.AddItem(item.Id)) { itemsAdded++; break; } //end code delay execution } } } } 

And I do not want to sleep, because when an item is added, I need to get confirmation from the server that the item was added.

+4
source share
2 answers

How about a simple time comparison?

 var lastExecution = DateTime.Now; if((DateTime.Now - lastExecution).TotalSeconds >= 3) ... 

You can save 'lastExecution' in your trading class. Of course, the code block is not called (elements are not added) with this solution if 3 seconds have not passed.

- // ---------------------------------

Various timer solutions: we add the Windows Forms timer component programmatically. But if you use this solution, you will end up programming hell ,-)

 //declare the timer private static System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer(); //adds the event and event handler (=the method that will be called) //call this line only call once tmr.Tick += new EventHandler(TimerEventProcessor); //call the following line once (unless you want to change the time) tmr.Interval = 3000; //sets timer to 3000 milliseconds = 3 seconds //call this line every time you need a 'timeout' tmr.Start(); //start timer //called by timer private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { Console.WriteLine("3 seconds elapsed. disabling timer"); tmr.Stop(); //disable timer } 
+2
source
  DateTime? lastCallDate = null; foreach (int id in allItems) { if (offered > 0 && itemsAdded != (offered * 3) && tDown) { List<Inventory.Item> items = Trade.MyInventory.GetItemsByDefindex(id); foreach (Inventory.Item item in items) { if (!Trade.myOfferedItems.ContainsValue(item.Id)) { //execute if 3 seconds have passed since it last execution... bool wasExecuted = false; while (!wasExecuted) { if (lastCallDate == null || lastCallDate.Value.AddSeconds(3) < DateTime.Now) { lastCallDate = DateTime.Now; if (Trade.AddItem(item.Id)) { itemsAdded++; break; } wasExecuted = true; } System.Threading.Thread.Sleep(100); } } } } } 
+1
source

All Articles