Kurogami
Kurogami

Reputation: 15

Checking time in every minute in C#

I'm making an application that will notify the user every 1, 5 or 30 minute or even every hour. For example the user opens the program in 5:06 and the program will notify the user in 6:06.

So my current code is notifying the user every 5 minutes using Thread.Sleep() function, but I find it kinda lame.

This is my code:

public void timeIdentifier()
    {
        seiyu.SelectVoiceByHints(VoiceGender.Female);
        while(true)
        {
            string alarm = String.Format("Time check");
            seiyu.Speak(alarm);
            string sayTime = String.Format(DateTime.Now.ToString("h:mm tt"));
            seiyu.Speak(sayTime);
            // It will sleep for 5 minutes LOL
            Thread.Sleep(300000);
        }
    }

Upvotes: 1

Views: 3801

Answers (3)

Boris Evraev
Boris Evraev

Reputation: 82

You can use Timer object (System.Threading). The timer object has interval not a timeout.

    static void Main(string[] args)
    {
        int firstCallTimeOut = 0;
        int callInterval = 300000;
        object functionParam = new object();//optional can be null
        Timer timer = new Timer(foo,null,firstCallTimeOut,callInterval);
       
    }
    static void foo(object state)
    {
       //TODO
    }

Upvotes: -1

George Mamaladze
George Mamaladze

Reputation: 7931

If you like newer .NET TPL syntax yo can write it like this:

internal class Program
{
    private static void Main(string[] args)
    {
        Repeat(TimeSpan.FromSeconds(10));
        Console.ReadKey();
    }

    private static void Repeat(TimeSpan period)
    {
        Task.Delay(period)
            .ContinueWith(
                t =>
                {
                    //Do your staff here
                    Console.WriteLine($"Time:{DateTime.Now}");
                    Repeat(period);
                });
    }
}

Upvotes: 0

Roman
Roman

Reputation: 12201

You can use Timers instead of Thread.Sleep():

public class Program
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        aTimer = new System.Timers.Timer(5000); // interval in milliseconds (here - 5 seconds)

        aTimer.Elapsed += new ElapsedEventHandler(ElapsedHandler); // handler - what to do when 5 seconds elaps

        aTimer.Enabled = true;

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    //handler
    private static void ElapsedHandler(object source, ElapsedEventArgs e)
    {
        string alarm = String.Format("Time check");
        seiyu.Speak(alarm);
        string sayTime = String.Format(DateTime.Now.ToString("h:mm tt"));
        seiyu.Speak(sayTime);
    }
}

Upvotes: 5

Related Questions