Ivajlo Iliev
Ivajlo Iliev

Reputation: 463

Define scheduled tasks in C#

I know that there are a lot of questions (and respectfully answers) related to this topic on this site, but as I am a newbie to C#, I still cannot figure out which solution works for me and that is why I decided to describe my situation here.

I write an application, which starts with the main method:

class Program
{
   static void Main(string[] args)
   {
   }
}

In this main method, I have to implement checking for new folders every 10 minutes.

I have another class defined for that - NewFoldersChecker, and static method in it "CheckForNewFolders"....so I hoped that a method in the class Program like this:

        private static void CheckForNewFolders()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    NewFoldersChecker.CheckForNewFolders();
                    await Task.Delay(60000);
                }


            });
        }

and calling it from the main method would do the job:

        static void Main(string[] args)
        {
            CheckForNewFolders();
        }

But obviously, this is not the case - the method is called once and that is all because the main thread ends.

What should I do to keep the main thread alive or what are my other options?

Upvotes: 0

Views: 91

Answers (1)

JonasH
JonasH

Reputation: 36341

I would highly recommend using a timer instead. These are made for running things periodically. Your Task.Delay is just a wrapper around a timer set to trigger a single time, so you are just making things more complicated for yourself.

For example:

static void Main(string[] args)
{
    using var aTimer = new System.Timers.Timer(60000);
    aTimer.Elapsed += OnTimedEvent;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;

    Console.WriteLine("Checking folders. press any key to exit");
    Console.ReadKey();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    // Check your folders here
}

Upvotes: 4

Related Questions