-2

I am absolutely new to C#. I'm trying to loop my code so that it executes every say 5 minutes. How can I do this, if at all possible?

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace GetRespond
{
    class Program
    {
        HttpClient client = new HttpClient();
        static async Task Main(string[] args)
        {
            Program program = new Program();
            await program.GetTodoItems();
        }

        private async Task GetTodoItems()
        {

            string response = await client.GetStringAsync("MY_WEBSITE_URL");

            Console.WriteLine(response);

        }

    }
}
Depotys
  • 11
  • 1

2 Answers2

2

Very straight forward with a loop and a delay:

class Program
{
    HttpClient client = new HttpClient();
    static async Task Main(string[] args)
    {
        Program program = new Program();
        while (true)
        {
            await Task.WhenAll( 
                program.GetTodoItems(), 
                Task.Delay( TimeSpan.FromMinutes(5) ) );
        }
    }

    private async Task GetTodoItems()
    {
        string response = await client.GetStringAsync("MY_WEBSITE_URL");
        Console.WriteLine(response);
    }
}
Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
1

You can use one from the way:

static async Task Main(string[] args)
{
    HttpClient client = new HttpClient();
    while (true)
    {
        await GetTodoItems(client);
        System.Threading.Thread.Sleep(5 * 60 * 1000); // 5 minutes * 60 seconds * 1000 ms
    }
}

private static async Task GetTodoItems(HttpClient client)
{
    string response = await client.GetStringAsync("MY_WEBSITE_URL");
    Console.WriteLine(response);
}

The solution is very simple and can be easy for your understanding as newbie. It have one trouble - thread-locking, by the way in your case it is possible as correct solution. Below you can see example for more efficiency (without thread-blocking):

static void Main(string[] args)
{
    // Start downloader with two args: time for sleep and url.
    StartDownloaderAsync(5,
    "https://stackoverflow.com/questions/68887441/how-to-repeat-my-code-in-loop-every-5-minutes-c",
    (result) => { Console.WriteLine(result); }); // You can replace Console.WriteLine(result) for any method where you can handle responce from downloader.
    Console.WriteLine("Downloader started, press 'S' for cancel.");

    while (true)
    {
        var key = Console.ReadKey();
        if (key.Key == ConsoleKey.S)
        {
            StopDownloaderAsync();
            break;
        }
    }

    Console.WriteLine("\nDownloader cancellation sent. Press any key for exit.");
    Console.ReadKey();
}

private static void StopDownloaderAsync()
{
    TokenSource.Cancel();
}

private static Task StartDownloaderAsync(int sleepTimeInMinutes, string url, Action<string> callback = null)
{
    HttpClient client = new HttpClient();
    return Task.Run(() =>
    {
        while (true)
        {
            try
            {
                Task<string> task = GetTodoItems(client, url);
                callback?.Invoke(task.Result);
            }
            catch (Exception ex)
            {
                callback?.Invoke(ex.Message);
            }
            int sleepTimeMs = sleepTimeInMinutes * 60 * 1000;

            Task waitTask = Task.Delay(sleepTimeMs, TokenSource.Token);
            waitTask.Wait();
            if (TokenSource.Token.IsCancellationRequested)
            {                        
                break;
            }
        }
    }, TokenSource.Token);
}

private static Task<string> GetTodoItems(HttpClient client, string url)
{
    Task<string> t = client.GetStringAsync(url);
    t.Wait();
    return t;
}
BVD
  • 33
  • 5