PeriodicTimer running inside a Task

310 Views Asked by At

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!

1

There are 1 best solutions below

0
psnx On

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.