Search code examples
c#timerstopwatch

Run a certain code every x minute


I'm trying to make a program whereby it does something every x minutes. I have been experimenting with the Stopwatch function but it don't seem to run the code I want when the time is up.

Here's my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;

namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch testing = new Stopwatch();
            testing.Start();

            Thread.Sleep(6001);
            TimeSpan ts = testing.Elapsed;
            int timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
            Console.Write(timer);

            while (testing.Elapsed < TimeSpan.FromMinutes(8))
            {

                timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
                if (timer % 60 == 0)
                {
                    //run x code every 1 minutes
                    Console.WriteLine("1 min" + timer);
                }


                timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
                if (timer % 120 == 0)
                {
                    //run x code every 2 minutes
                    Console.WriteLine("2 min" + timer);
                }
            }    

            testing.Stop();
        }
    }
}

Solution

  • As suggested by xxbbcc, here's an implementation using ManualResetEvent.WaitOne() with a TimeOut:

        static void Main(string[] args)
        {
            int TimeOut = (int)TimeSpan.FromMinutes(2).TotalMilliseconds;
            System.Threading.ManualResetEvent mreDuration = new System.Threading.ManualResetEvent(false);
            Task.Run(() => {
                System.Threading.Thread.Sleep((int)TimeSpan.FromMinutes(30).TotalMilliseconds);
                mreDuration.Set();
            });
            while(!mreDuration.WaitOne(TimeOut))
            {
                Console.WriteLine("Two Minutes...");
            }
            Console.WriteLine("Thirty Mintues!");
            Console.ReadLine();
        }