Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have developed a c# Console Application which executes an SQL Command and display the output of the query in the console. Now i need to Execute the same Query which is present in the Program for every 2 Minutes. So that the previous output should be cleared and display the fresh output of that query. I have tried with some Threading and sleep functions, but i was unable to do it. I have kept time interval as 30 Seconds, But after 30 Seconds the window is getting closed.

The code Which i have was:-

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace LeakLocationFinder
{
 class Program
  {
 static void Main(string[] args)
    {
  using (SqlConnection conn = new SqlConnection())
      {        
  conn.ConnectionString = "server=(local);database=modelDb;user id=sa;pwd=123456";
  conn.Open();
             
SqlCommand command = new SqlCommand("DECLARE @var varchar(1000) = (SELECT TOP 1 Text FROM Alarms WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC) DECLARE @start_position int, @end_position int SELECT @start_position = PATINDEX('% at%', @var) SELECT @end_position = PATINDEX('%kilometers%', @var) DECLARE @VALUE VARCHAR(10) = (Select SUBSTRING(@var, @start_position+5,5)) Select Top 1 @VALUE,RouteTable.Latitude,Routetable.Longitude,Alarms.EventTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC", conn);

using (SqlDataReader reader = command.ExecuteReader())
          {
 Console.WriteLine("Column1\t\tColumn2\t\tColumn3\t\t");
                    while (reader.Read())
             {
      Console.WriteLine(String.Format("\t{0} \t\t | {1} \t\t | {2} \t",
                            reader[0], reader[1], reader[2]));
              }
           }

         }
      }
    }
}
Posted
Comments
Sinisa Hajnal 10-Apr-15 3:04am    
Use Timer component and on each timer tick trigger your function. That's what it is for.

You could also try something like this, does about the same as Florian's answer but just a bit more basic.

C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace LeakLocationFinder
{
 class Program
  {
 static void Main(string[] args)
    {
  Console.Clear();
  using (SqlConnection conn = new SqlConnection())
      {
  conn.ConnectionString = "server=(local);database=modelDb;user id=sa;pwd=123456";
  conn.Open();

SqlCommand command = new SqlCommand("DECLARE @var varchar(1000) = (SELECT TOP 1 Text FROM Alarms WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC) DECLARE @start_position int, @end_position int SELECT @start_position = PATINDEX('% at%', @var) SELECT @end_position = PATINDEX('%kilometers%', @var) DECLARE @VALUE VARCHAR(10) = (Select SUBSTRING(@var, @start_position+5,5)) Select Top 1 @VALUE,RouteTable.Latitude,Routetable.Longitude,Alarms.EventTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC", conn);

using (SqlDataReader reader = command.ExecuteReader())
          {
 Console.WriteLine("Column1\t\tColumn2\t\tColumn3\t\t");
                    while (reader.Read())
             {
      Console.WriteLine(String.Format("\t{0} \t\t | {1} \t\t | {2} \t",
                            reader[0], reader[1], reader[2]));
              }
           }

         }
         Thread.Spleep(time);
         Refresh(args);
         Console.ReadKey();
      }
      public static void Refresh(string[] reff)
        {
            Main(reff);

        }
    }
}
 
Share this answer
 
Use Timer...it works without you needing to pause the whole thread.

C#
using System;
using System.Timers;

public class Example
{
   private static Timer aTimer;

   public static void Main()
   {
        // Create a timer 
        aTimer = new System.Timers.Timer(120000);
        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += OnTimerElapsed;
        aTimer.Start();
// do whatever
   }

    private static void OnTimerElapsed(Object source, ElapsedEventArgs e)
    {

// do some work here (get the database data etc...)
    }
}
 
Share this answer
 
Comments
Florian Braun 10-Apr-15 6:38am    
of course timers are cool for repeating tasks.. but if you have an application for console you still need some loop to stay within the program AND if your program doesnt do anything else timers are as useless as waiting without doing anything
Sinisa Hajnal 10-Apr-15 9:03am    
Not true. You could show whatever you want on the screen ending with do you want to quit question (or simple press any key...). As long as the timer works it will refresh...and at some point it will exit when do user wants to stop it. If the thread is blocked, there is no way to end it except Ctrl+C
Florian Braun 10-Apr-15 9:07am    
not really true. i totally agree that timers are great but i just wanted to show they are maybe not the best solution here as simply not necessary. I presented a solution where the user can quit at ANYTIME by pressing a key but it was not what the guy who asked the question wanted so i removed that feature.
without knowing more about your database i'd add:

C#
List<string> newList=new List<string>();
List<string> oldList=new List<string>();
bool firstrun=true;

do{
 
    using (SqlDataReader reader = command.ExecuteReader())
    {
         newList.clear();
         Console.clear(); //delets the Console
         Console.WriteLine("Column1\t\tColumn2\t\tColumn3\t\t");
              
         while (reader.Read())
         {
              string line=String.Format("\t{0} \t\t | {1} \t\t | {2} \t",
                            reader[0], reader[1], reader[2]);

              Console.WriteLine(line);
              newList.Add(line);
          }
     }
 
     if (!firstrun){
          if (newList.Count!=oldList.Count) {
              Messagebox.Show("Count of Lines has changed!");
          }
          else {
              for (int i=0;i<newlist.count;i++){
                  if (newList[i]!=oldList[i]) {
                       Messagebox.Show("At least one line has changed");
                       break;
                   }
              }
       }
     else firstrun=false; 

     oldList.Clear();
     for (int i=0;i<newlist.count;i++)oldlist.add(newlist[i]);
             
     Thread.Sleep(120000);
} while (true);




also you will need to add using System.Windows.Forms; and if you get an error (namespace not found, missing assembly) the reference to System.Windows.Forms
 
Share this answer
 
v2
I don't think there is any need for threading if waiting and SQL-Output is all what your programm is doing.

So my suggestion is

C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
 
namespace LeakLocationFinder
{
 class Program
  {
 static void Main(string[] args)
    {
  using (SqlConnection conn = new SqlConnection())
      {        
  conn.ConnectionString = "server=(local);database=modelDb;user id=sa;pwd=123456";
  conn.Open();
             
SqlCommand command = new SqlCommand("DECLARE @var varchar(1000) = (SELECT TOP 1 Text FROM Alarms WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC) DECLARE @start_position int, @end_position int SELECT @start_position = PATINDEX('% at%', @var) SELECT @end_position = PATINDEX('%kilometers%', @var) DECLARE @VALUE VARCHAR(10) = (Select SUBSTRING(@var, @start_position+5,5)) Select Top 1 @VALUE,RouteTable.Latitude,Routetable.Longitude,Alarms.EventTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC", conn);

do{
 
    using (SqlDataReader reader = command.ExecuteReader())
    {
         Console.clear(); //delets the Console
         Console.WriteLine("Column1\t\tColumn2\t\tColumn3\t\t");
         
         while (reader.Read())
         {
              Console.WriteLine(String.Format("\t{0} \t\t | {1} \t\t | {2} \t",
                            reader[0], reader[1], reader[2]));
          }
     }
 

     Thread.Sleep(120000);
} while (true);
}
}
}
}

(I hope I closed all curly brakets)
 
Share this answer
 
v4
Comments
Krishna Chaitanya Bezawada 10-Apr-15 4:30am    
Thanks for the Solution. But I have tried the code which you have given. Now it was Continuously executing the SQL Query and giving the output in the console Window. But Every time it executing, it is writing output after the previous Execution output. I need to clear the Previous Output, and write the new output in the first line.

And if we press any key the console is stopping execution and closing the Console Window.

I have removed the Console.Readkey(true); statement, but it is still closing the console when any key is pressed.

Please help me with this.
Florian Braun 10-Apr-15 4:37am    
Console.Clear() gets you a fresh and empty console. Did you add it?

I added "Console.KeyAvailable" to give you a chance to quit the programm. if you don't want this feature you can:
* change the first while (!Console.KeyAvailable) to while (true)
* change sleep(120000) to Thread.Sleep(120000) and remove the whole additional function "public static void sleep..."
Krishna Chaitanya Bezawada 10-Apr-15 5:47am    
yes, I have used console.clear() but there is no use. And Can you please update the above Solution, So that where you are asking me to change the While. As if i update the While function as said by you it is returning an error.
Krishna Chaitanya Bezawada 10-Apr-15 5:48am    
The application should not exit even when we press any key.
Krishna Chaitanya Bezawada 10-Apr-15 5:49am    
And if i update sleep to thread.Sleep(120000) it was returning an error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900