Home > Net >  Where to put method call so it execute at every 5 minutes
Where to put method call so it execute at every 5 minutes

Time:11-21

I have below code :

public async Task StartAsync(CancellationToken cancellationToken)
{
    var cronExpressionVal = new Timer(async e => await GetCronExpression(cancellationToken), null, TimeSpan.Zero, new TimeSpan(0, 5, 0));
}

What I am trying to achieve is, GetCronExpression method should run at every 5 minutes.

But my problem is, when we first time run programme so it is coming in StartAsync method.

And it execute successfully.

Now it is not coming again in this method so my GetCronExpression method is not calling at every 5 minutes.

So my question is where should I put this GetCronExpression method call so it execute at every 5 minutes.

CodePudding user response:

You have to keep reference to timer otherwise it will be garbage collected:

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

enter image description here

Implementation Using Any Custom Class/Anywhere:

            var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));

            int counter = 0;
            while (await timer.WaitForNextTickAsync())
            {
                counter  ;
                if (counter > 5) break;
                CallThisMethodEvery5Second(counter);
            }

Note: You will call your method GetCronExpression within the WaitForNextTickAsync so that will be called at your given time frame. For the demo, I am calling this in every 5 seconds.

Method To Call:

public void CallThisMethodEvery5Second(int counter)
        {
            Console.WriteLine("Current counter: {0} Last Fired At: {1}",counter, DateTime.Now);
        }

Output:

enter image description here

  • Related