如何使应用程序永远不会关闭并每小时执行一次程序?

问题描述 投票:0回答:3

怎么样!有人可以帮我解决这个问题,我正在寻找的是通过控制台应用程序每次“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");
                            }
                        }
                    }
                }
            }
        }
    }
}
c# for-loop stored-procedures while-loop console-application
3个回答
0
投票

如评论中所述,满足您需求的最佳方法是删除循环并仅执行一次操作,并创建任务计划以在所需时间运行程序。

如果您需要继续使用相同的方法来解决此代码必须面对的一些问题:

如果插入操作不到一分钟,它每隔一小时就会插入一次。示例:如果插入在1:00:00开始并在1:00:20结束,则程序将开始下一次迭代并再次插入,因为mm仍然是00.其中一个解决方案是让线程进入休眠状态从外环内部1分钟。

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


0
投票

只需使用计时器。

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();
    }
}

0
投票

如果采用async / await并使用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}");
    }
}

将此代码转换为在小时而不是在第二小时触发应该是微不足道的。一个很好的运动。

© www.soinside.com 2019 - 2024. All rights reserved.