I need to build a service that will run theoretically forever.
While running it will need to check a local cache once every couple of seconds, and if it finds new items in that cache it should create and execute a new Task for each new item.
My question is, what is a good approach to implementing such a service? My main concern is how should I do the time-based starting of async tasks.
I came up with two ways to do this
- Use a - System.Timers.Timerto push events and then run code when the event is fired
- Create a method that will call itself using - Task.Delay
Here are some examples of what I mean by those two methods:
Timer
public void Run()
{
    System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromSeconds(2).TotalMilliseconds);
    CancellationTokenSource ts = new CancellationTokenSource();
    timer.Elapsed += async (sender, argz) => await CodeExecutor(ts.Token);
    timer.Start();
}
public async Task CodeExecutor(CancellationToken token)
{
    //Some logic
}
Task.Delay
private async Task RepeatableMethod(CancellationToken cancellationToken)
{
    try
    {
        //some logic
    }
    catch (Exception e)
    {
    }
    finally
    {
        await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken)
            .ContinueWith(_ => RepeatableMethod(cancellationToken),cancellationToken);
    }
}
I am not sure which method would better fit my scenario, and if there isn't a different way that would be even better than those two. My main concern is that I want the logic that I am executing every 2 seconds to be asynchronous and possibly parallel.
What would be considered a better approach in the following scenario, and is there another (good) way I can approach my case?
 
     
     
    