How to write C# Scheduler

后端 未结 6 1507
故里飘歌
故里飘歌 2020-12-31 14:40

How do I write a Alert which will run at 00:00, 00:15, 00:30, and so on every day?

Can you give me an example code?

Thank you.

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 15:14

    Here is a basic C# scheduler:

    using System;
    using System.Threading;
    using System.Windows.Forms;
    using System.IO;
    
    public class TimerExample
    {
        public static void Main()
        {
            bool jobIsEnabledA = true;
            bool jobIsEnabledB = true;
            bool jobIsEnabledC = true;
    
            Console.WriteLine("Starting at: {0}", DateTime.Now.ToString("h:mm:ss"));
    
            try
            {
                using (StreamWriter writer = File.AppendText("C:\\scheduler_log.txt"))
                {
                    while (true)
                    {
                        var currentTime = DateTime.Now.ToString("h:mm");
    
                        if (currentTime == "3:15" && jobIsEnabledA)
                        {
                            jobIsEnabledA = false;
                            ThreadPool.QueueUserWorkItem((state) => { MessageBox.Show(string.Format("Time to brush your teeth! {0}", currentTime) ); });
                        }
    
                        if (currentTime == "3:20" && jobIsEnabledB)
                        {
                            jobIsEnabledB = false;
                            ThreadPool.QueueUserWorkItem((state) => { MessageBox.Show(string.Format("Time to brush your teeth! {0}", currentTime)); });
                        }
    
                        if (currentTime == "3:30" && jobIsEnabledC)
                        {      
                            jobIsEnabledC = false;
                            ThreadPool.QueueUserWorkItem((state) => { MessageBox.Show(string.Format("Time for your favorite show! {0}", currentTime)); });
                        }
    
                        if (currentTime == "3:31")
                        {      
                            jobIsEnabledA = true;
                            jobIsEnabledB = true;
                            jobIsEnabledC = true;
                        }
    
                        var logText = string.Format("{0} jobIsEnabledA: {1} jobIsEnabledB: {2} jobIsEnabledC: {3}", DateTime.Now.ToString("h:mm:ss"), jobIsEnabledA, jobIsEnabledB, jobIsEnabledC);
                        writer.WriteLine(logText);
    
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
    }
    

提交回复
热议问题