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;
}