-2

I have a condition in my project where I have to hit an API after every 5 secs.

while(true)
{
    // here I have to call the method after every 5 secs
    method();
}
Utmost Creator
  • 814
  • 1
  • 9
  • 21
Rabner Casandara
  • 151
  • 3
  • 18
  • 3
    You wouldn't usually do this in a loop, use a timer instead. – DavidG Nov 01 '21 at 12:22
  • 1
    yeah, you must not use a loop for such cases, timer is a good solution. Have a look [How to implement setInterval(js) in C#](https://stackoverflow.com/a/41081355/6901693) – Utmost Creator Nov 01 '21 at 12:24

1 Answers1

1

As I already has been said, use a Timer instead. ie:

void Main()
{
  var t = new System.Timers.Timer(1000){Enabled = true};
  t.Elapsed += (sender, args) => { 
    Console.WriteLine(DateTime.Now);
  };
}

EDIT: Example of a progress bar counting 30 (30000 millis) seconds.

void Main()
{
  Form f = new Form();
  ProgressBar pb = new ProgressBar { Maximum=30000, Left=10, Top=10, Width=200 };
  Label l = new Label {Top=50,Left=10,Text=""};
  
  var t = new System.Timers.Timer(1000){Enabled = false};
  
  f.Controls.Add( pb );
  f.Controls.Add( l );
  
  f.Show();

  var start = DateTime.Now;
  t.Elapsed += (sender, args) => { 
      var elapsed = (int)(DateTime.Now - start).TotalMilliseconds;
      pb.Value=Math.Min(elapsed, pb.Maximum); 
      l.Text = (elapsed/1000).ToString();

      if (elapsed >= pb.Maximum)
      {
        t.Enabled = false;
      }
  };
  t.Enabled = true;
}
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
  • Can you give some explanation of it ? – Rabner Casandara Nov 01 '21 at 12:47
  • @RabnerCasandara, it simply initializes a system timer, that is running every 1000 milliseconds, and when it does, its Elapsed event is invoked. In Elapsed you can call your method, I simply output current datetime to console. Your other code can continue to run, this would fire once a second (initialized with an Interval of 1000 milliseconds). In your case you would initialize with 5000. As an example I am adding a progressbar on a form. – Cetin Basoz Nov 01 '21 at 13:50