C# 如何使应用程序永不关闭并每小时执行一个过程?

C# 如何使应用程序永不关闭并每小时执行一个过程?,c#,for-loop,stored-procedures,while-loop,console-application,C#,For Loop,Stored Procedures,While Loop,Console Application,怎么样!,有人可以帮我,我要找的是,通过控制台应用程序,每次“00”分钟(即每小时),存储过程只执行一次(我不知道为什么它运行超过1次,因为它是一个插入过程),我还希望应用程序永远不要关闭,稍后我想创建一个服务并执行更多的过程,但我暂时需要它。我做错了什么?我的想法是在控制台中写入“等待批量插入”,当时间到来时,执行过程并写入“成功插入”,然后继续键入“等待批量插入”,直到下一个小时到来 using System; using System.Data; using System.Data.Sql

怎么样!,有人可以帮我,我要找的是,通过控制台应用程序,每次“00”分钟(即每小时),存储过程只执行一次(我不知道为什么它运行超过1次,因为它是一个插入过程),我还希望应用程序永远不要关闭,稍后我想创建一个服务并执行更多的过程,但我暂时需要它。我做错了什么?我的想法是在控制台中写入“等待批量插入”,当时间到来时,执行过程并写入“成功插入”,然后继续键入“等待批量插入”,直到下一个小时到来

using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;

namespace Job_StoreProcedure
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SqlConnection conn = new SqlConnection
                  ("Server=localhost\\SQLEXPRESS;Database=VIDEOJUEGOS;Integrated Security=SSPI"))
            {
                conn.Open();
                for (int i = 0; i - 1 < i++; i++)
                {
                    Console.WriteLine("Waiting for insertion in batch");
                    if (DateTime.Now.ToString("mm") == "00")
                    {
                        SqlCommand cmd = new SqlCommand("usp_virtualX", conn);
                        cmd.CommandType = CommandType.StoredProcedure;

                        using (SqlDataReader rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                Console.WriteLine("Successful insertion");
                            }
                        }
                    }
                }
            }
        }
    }
}
使用系统;
使用系统数据;
使用System.Data.SqlClient;
使用系统线程;
名称空间作业存储过程
{
班级计划
{
静态void Main(字符串[]参数)
{
使用(SqlConnection conn=newsqlconnection
(“Server=localhost\\SQLEXPRESS;Database=VIDEOJUEGOS;integratedsecurity=SSPI”))
{
conn.Open();
对于(int i=0;i-1
如评论中所述,满足您需求的最佳方法是删除循环并仅执行一次操作,并创建任务计划以在所需时间运行程序

如果需要继续使用相同的方法,则此代码必须面临的一些问题:

如果插入操作所需时间少于一分钟,则每小时将插入一次以上。示例:假设插入在1:00:00开始,在1:00:20结束,程序将开始下一次迭代,并将再次插入,因为mm仍然是00。解决方案之一是将线程从外环内部休眠1分钟

这段代码还将面临一个问题,即在一段时间内未使用时,连接将关闭。此外,当插入失败时,由于没有错误处理,程序将退出。您可能希望在执行操作(即内部循环)时打开和关闭连接,并在出现异常时使用错误处理保持应用程序运行。

只需使用计时器即可

using System.Timers;
//...
class Program
{
    private static Timer MainTimer = new Timer(1000 * 60 * 60);

    static void Main(string[] args)
    {
        Console.WriteLine("Waiting for insertion in batch");

        MainTimer.Elapsed += MainTimer_Elapsed;

        // Wait for the start of the hour. Then start the one-hour MainTimer. 
        var tmptimer = new Timer() { Interval = 1000 };
        tmptimer.Elapsed += (sender, e) =>
        {
            if (DateTime.Now.Minute == 0)
            {
                MainTimer.Start();              
                tmptimer.Stop();
                MainTimer_Elapsed(null, null);  // Call manually first time 
            }
        };
        tmptimer.Start();

        while (true)
            Console.Read();
    }

    private static void MainTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (SqlConnection conn = new SqlConnection ("Server=localhost\\SQLEXPRESS;Database=VIDEOJUEGOS;Integrated Security=SSPI"))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("usp_virtualX", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    Console.WriteLine("Successful insertion");
                }
            }
        }
        Console.WriteLine("Waiting for insertion in batch");

        GC.Collect();
    }
}

如果您采用
async
/
wait
并使用
Task.Delay
:

例如,您可以:

static async Task Main(string[] args) //async Main supported in C#7
{
    var now = DateTime.UtcNow; //always use UTC, calculating timezones costs time
    var startOfCurrentTimePeriod = 
        new DateTime(now.Year, 
                     now.Month, 
                     now.Day, 
                     now.Hour, 
                     now.Minute, 
                     now.Second, 
                     0,         //set this ms part to 0
                     DateTimeKind.Utc);
    var triggerTime = oClock.AddSeconds(1); //when we want to run our action
    while (true)
    {
        var waitTime = triggerTime - DateTime.UtcNow;
        if (waitTime > TimeSpan.Zero) //if we have a negative wait time, just go
        {
            await Task.Delay(waitTime);
        }
        triggerTime = triggerTime.AddSeconds(1); //set the next time
        //perform action
        Console.WriteLine($"the time is : {triggerTime}");
    }
}

将此代码转换为在小时而不是秒触发应该很简单。一个很好的练习。

更好的选择是删除循环并创建正常程序。ln使用windows或任何其他调度器将其计划为每小时运行一次。让程序等待并且永不退出是不好的idea@PriyeshKumar他们已经发布了。问题是如何在控制台应用程序中“暂时”这样做。计算机将在一天结束时得到支付,最后我想返回一个服务中的.exe,该服务在计算机打开并且控制台应用程序开始工作时启动,正如我所说的,因为现在它只带有一个存储过程,但我计划添加更多作业,但我想让结构武装起来。您能帮助我吗?您是否考虑过使用SQL Server代理简单地调度存储过程?您也可以使用observer设计模式从头创建调度器。