-1

I have a top-level class that is a long-running management class for various requirements for my application.

I need to have some kind of Timer set-up which will monitor any errors around my application, pausing a Quartz Scheduler execution for x minutes and then perform certain actions on the back of it.

Once the Class is fully configured, I call the below Method:

private async Task BeginActionMonitoring()
{
      var _actionMonitoringTimer = new PeriodicTimer(TimeSpan.FromSeconds(30));
      while (await _actionMonitoringTimer.WaitForNextTickAsync())
      {
          await ExecuteErrorCheckActions();
      }
}

The problem I have is that I don't want to have the whole class dormant and stuck within a While-Loop.

Is there a best-practice of how to handle this and have it running parallel with the Class?

Is the below the correct way to do this?

private async Task BeginActionMonitoring()
{
      var _actionMonitoringTimer = new PeriodicTimer(TimeSpan.FromSeconds(30));

      Task.Run(() => {
             while (await _actionMonitoringTimer.WaitForNextTickAsync())
             {
                 await ExecuteErrorCheckActions();
             }
      });
}

Thanks!

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Paul James
  • 121
  • 2
  • 7
  • 1
    *"The problem I have is that I don't want to have the whole class dormant and stuck within a While-Loop."* -- Why? Could you edit the question and explain what's the problem in more details? What's the actual observable undesirable effect that you want to prevent? – Theodor Zoulias Jun 17 '23 at 08:41
  • 1
    There is no such concept of a class running. Your first snippet is fine. – Fildor Jun 17 '23 at 10:26
  • 1
    Even ignoring how much of a code smell the second snippet is, it's also broken -- you never await anything in it despite declaring it as `async`. – Blindy Jun 17 '23 at 15:58

1 Answers1

-1

You can use a timer for this purpose, without a Task, but you can of course run it inside a task too.

var _timer = new System.Timers.Timer(TimeSpan.FromSeconds(30));

Then use it like so:

_timer.Elapsed += (_, _) => DoSomeChecks();
_timer.Enabled = true;

you can disable it if need be by setting the Enabled property to false.

psnx
  • 618
  • 7
  • 8