在控制台应用程序c#中使用time hour执行查询

时间:2015-12-26 03:32:56

标签: c#

我想使用带参数hour的控制台应用程序来截断表。 例如,我想在上午12点使用系统中的时间运行查询截断。

这是我在使用c#的控制台应用程序中的代码。

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {            
            string getHour = DateTime.Now.ToString("h:mm:ss tt");

            if (getHour == "12:00:00 AM")
            {
                Console.WriteLine("Do action to run query truncate");
                //in this line i will execute query truncate.
            }        

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        } 
    }
}

这不起作用。请给我解决方案或示例代码来解决我的问题。 感谢...

4 个答案:

答案 0 :(得分:1)

当你运行你的程序时,它会快速查看时钟,如果它不是正好在午夜就会立即退出。 (更准确地说,它打印一些消息并等待直到按下)。我相信你希望等到午夜。如果准确的时间不那么重要(我的意思是早或晚可以接受几秒钟),最简单的解决方案是:

end - start

答案 1 :(得分:1)

我觉得问题在于代码的执行流程。 您只需调用一次代码然后停止。它现在检查一次并获得当前时间。如果时间是凌晨12:00:00,你可以传入if语句,但是你需要在点上的12:00:00系统时间运行它,这几乎是不可能的。

您应该考虑使用Windows服务或使用Windows任务管理器:C# Console Application - Keep it running

答案 2 :(得分:1)

正如其他答案所述,您不应该使用您的应用来安排任务。看起来你正在做一个数据库维护任务,所以我要看的第一件事是......

1)查看您的数据库是否可以安排任务。例如, SQL Server代理可以计划在设定的时间运行存储过程(或adhoc SQL),如果您将数据库用于数据库,则可以完成任务。 More info here

如果您的数据库无法执行此操作,或者您希望执行除截断表之外的其他操作...

2)尝试使用 Windows任务计划程序

这可以在设定的时间启动应用程序,易于设置,然后您的应用程序可以完成它的意思(例如截断表格),而不用担心安排。

答案 3 :(得分:1)

我会在你的代码上提出一些建议:

  1. 请勿使用string比较,但直接使用DateTime(请查看TimeOfDay.TotalSeconds)。通过这种方式,它使比较变得更加容易
  2. 使用重复调用而不是一次调用(除非您确实可以确定您在12处完全运行程序)。通过这种方式,您可以使您的程序更适合您。
  3. 为了使其更加健壮,请提供一些方法来为您的系统提供容忍度。这就是良好的自动化程度。
  4. 示例:

    namespace ConsoleApplication1 {
        class Program {
            static void Main(string[] args) {
    
                while (true) { //read 2. assuming this is to be run forever in this example, but gives also some way to break the loop whenever necessary in your app
                    if (DateTime.Now.TimeOfDay.TotalSeconds <= 1) { //read 1. and 3. this way, you give tolerance of 1 second. Your action will be run on 12:00:00 - 12:00:01
                        Console.WriteLine("Do action to run query truncate");
                        //  //in this line i will execute query truncate.
                        break; //break after saving once, for instance, and run again when the time close... This is to prevent possible multiple executions...
                    }
                    System.Threading.Thread.Sleep(500); //read 2. and 3. check every 500 millisecond, at least to give chance to check the time twice per second
                }
    
                // Keep the console window open in debug mode.
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
    }