A simple Recurring Task using C# and .NET

Nitin Manju
1 min readAug 30, 2019

--

To implement a simple recurring task in C# .NET, all you need is the following:

System.Threading.Tasks.Task

System.TimeSpan

System.Action

System.Threading.CancellationToken

System.Threading.CancellationTokenSource

static void RT(Action action, int seconds, CancellationToken token) 
{
if (action == null)
return;
Task.Run(async () => {
while (!token.IsCancellationRequested)
{
action();
await Task.Delay(TimeSpan.FromSeconds(seconds), token);
}
}, token);
}

Calling the method RT (short for Recurring Task) is pretty simple!

static void Main(string[] args)
{
var cts = new CancellationTokenSource();

RT(() => Console.WriteLine("Hello again!"), 4, cts.Token);
Console.ReadKey();
}

Pass an action method that you would like to be executed in a recurring fashion, an interval in seconds and a cancellation token to cancel the task at any point later.

It has to be noted that if the set interval is small while the action is time consuming, it would be up to you to either choose to make the action run as an async task or combine the execution time with the time delay.

As you can see, I have used an integer to set the timer for seconds. you can change this to suit your use-case and it should still work fine.

Thanks for reading!

--

--