Run a query every 2 seconds.

답변됨 Run a query every 2 seconds.

  • 2012년 5월 1일 화요일 오전 9:39
     
      코드 있음

    Dear All,

                I have an application where I would like to run a query every seconds based on the current time. So I started a thread for that but I got stuck at the onStart and onStop method. I would like to check too if thread is still running then do not let next one run till the previous is done.

    Error 1 'win3.Form1.OnStart(string[])': no suitable method found to override C:\Documents and Settings\ns\My Documents\Visual Studio 2010\Projects\win3\win3\Form1.cs 25 33 win3

    Error 2 'win3.Form1.OnStop()': no suitable method found to override C:\Documents and Settings\ns\My Documents\Visual Studio 2010\Projects\win3\win3\Form1.cs 31 33 win3

    Below is my codes

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using MySql.Data.MySqlClient;
    using System.IO;
    using System.Threading;
    namespace win3
    {
        public partial class Form1 : Form
        {
            private Thread doWorkThread;
    
            private bool existThread = false;
            
            public Form1()
            {
                InitializeComponent();
                this.doWorkThread = new Thread(new ThreadStart(DoWork));
            }
            protected override void OnStart(string[] args)
            {
    
                this.doWorkThread.Start(); // Start The Thread
            }
    
            protected override void OnStop()
            {
                this.existThread = true;
            }
            private void DoWork()
            {
                MessageBox.Show("TEST");
                while (true)
                {
    
                    if (this.existThread) 
                        return;
                    //to run my query every 2 seconds
                    Thread.Sleep(TimeSpan.FromSeconds(20));
                }
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                
            }
    }
    


모든 응답

  • 2012년 5월 1일 화요일 오전 10:06
     
     답변됨

    Greetings.

    You really should not be using Sleep to get a two second interval. You should use a Windows.Forms.Timer to trigger an event every 2 seconds.

    Check the help here...

    http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
    • 답변으로 제안됨 Link.fr 2012년 5월 1일 화요일 오전 11:06
    • 답변으로 표시됨 a.net sukbir 2012년 5월 2일 수요일 오전 7:09
    •  
  • 2012년 5월 1일 화요일 오전 10:33
     
     

    Hi Ante Meridian,

    Can you please explain why should we not use Sleep and prefer timer?

    Anything wrong with that?

    I'm curious to know.

    Thanks in advance.


    Always mark the answers if the post answers your question. Prabhu R

  • 2012년 5월 1일 화요일 오전 11:01
     
     

    Sleep tends to be inexact because after you have paused for, say 2 seconds, there will be lines of code that execute before you get back to the next sleep, so there will be more than 2 seconds between operations. Exactly how much more, you can't tell in advance.

    Essentially, Sleep is a blunt instrument, whereas timers are designed to perform tasks at exact intervals.
  • 2012년 5월 1일 화요일 오전 11:11
     
     

    So you mean that whenever the timer is elapsed, it will directly handle that event and execute our stuff?

    It will not queue it to the OS scheduler and wait for its turn as like in Round Robin methods.

    Is that what you mean as difference between Sleep and Timer?


    Always mark the answers if the post answers your question. Prabhu R

  • 2012년 5월 1일 화요일 오전 11:22
     
     

    I don't know what a Round Robin method is, but essentially yes. If you tell a timer to send you a tick every two seconds, then every two seconds your event handler will be invoked.

    Sleep, on the other hand, just tells your thread to not do anything for two seconds. That doesn't guarantee that the next time your method is called will be two seconds after the first one, because you don't know what else might happen in the meantime.


    • 편집됨 Ante Meridian 2012년 5월 1일 화요일 오전 11:23 Replace application with thread.
    •  
  • 2012년 5월 1일 화요일 오후 5:34
     
      코드 있음

    Dear Ante,

                     I tried the linked and modified the codes as below. It calls the

    MessageBox.Show("Time now is : " + DateTime.Now);

    for the current time. The problem is not showing consistent at every 5 seconds. So what could be reason?

    static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
            
            static int alarmCounter = 1;
            static bool exitFlag = false;
    
            // This is the method to run when the timer is raised.
            private static void TimerEventProcessor(Object myObject,
                                                    EventArgs myEventArgs)
            {
                myTimer.Stop();
    
                MessageBox.Show("Time now is : " + DateTime.Now);
                myTimer.Enabled = true;
                // Displays a message box asking whether to continue running the timer.
                /*if (MessageBox.Show("Continue running?", "Count is: " + alarmCounter,
                   MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    // Restarts the timer and increments the counter.
                    alarmCounter += 1;
                    myTimer.Enabled = true;
                }
                else
                {
                    // Stops the timer.
                    exitFlag = true;
                }*/
            }
            
            public Form1()
            {
                InitializeComponent();
            }
            
            
            private void Form1_Load(object sender, EventArgs e)
            {
                myTimer.Tick += new EventHandler(TimerEventProcessor);
    
                // Sets the timer interval to 5 seconds.
                myTimer.Interval = 5000;
                myTimer.Start();
            }
    }

  • 2012년 5월 1일 화요일 오후 11:39
     
     

    Greetings.

    Every time you stop and restart the timer, it starts counting from that moment. So it will report 5 seconds from when you hit OK in the MessageBox, not 5 seconds from the last event.So if you take two seconds to hit OK after the message box appears, the next event will be seven seconds from the last one.

    Take out myTimer.Stop() and myTimer.Enabled = true, and you should see consistent 5 second intervals.

  • 2012년 5월 2일 수요일 오전 5:14
     
      코드 있음

    Dear Ante,

                    Below is my latest codes. What I am trying to achieve is update the graph on a live data which is being inserted into the db? Can you give me your idea if I am doing it correctly now? I want to live updates on the graph? Thank you.

    public partial class Form1 : Form
        {
            static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
            
            static int alarmCounter = 1;
            static bool exitFlag = false;
    
            // This is the method to run when the timer is raised.
            private  void TimerEventProcessor(Object myObject,
                                                    EventArgs myEventArgs)
            {
                //myTimer.Stop();
    
                MessageBox.Show("Time now is : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
    
                MySqlConnection localConnection1;
                MySqlCommand command;
    
                localConnection1 = new MySqlConnection("Address='******';Database='****';User Name='****';Password='*****';Pooling='false'");
                MySqlDataAdapter myLocalDataAdapter1 = new MySqlDataAdapter();
    
                String mySelectQuery1 = "Select  " +
                                        "sum(pc) as sumPC" +
                                        "timeStampID " +
                                        "From byteTransmit Where timeStampID='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
    
                MessageBox.Show(mySelectQuery1);
                MySqlCommand myCommand1 = new MySqlCommand(mySelectQuery1, localConnection1);
                DataTable myDataTable1 = new DataTable();
                myLocalDataAdapter1.SelectCommand = myCommand1;
                myLocalDataAdapter1.Fill(myDataTable1);
    
    
                chart1.DataSource = myDataTable1;
    
                chart1.DataBind();
    
                chart1.Series["SE"].XValueMember = "timeStampID";
    
                chart1.Series["SE"].YValueMembers = "sumPC";
    
    
    
    
    
    
    
               
            }
            
            public Form1()
            {
                InitializeComponent();
            }
            
            
            private void Form1_Load(object sender, EventArgs e)
            {
                myTimer.Tick += new EventHandler(TimerEventProcessor);
    
                // Sets the timer interval to 5 seconds.
                myTimer.Interval = 50000;
                myTimer.Start();
                
                
            }
        }
    }

  • 2012년 5월 2일 수요일 오전 5:25
     
      코드 있음

    // Sets the timer interval to 5 seconds. myTimer.Interval = 50000;

    Why is your interval 50 seconds when you wanted for 5 seconds? It should be 5000.

    Always mark the answers if the post answers your question. Prabhu R

  • 2012년 5월 2일 수요일 오전 5:58
     
     

    Greetings again.

    The Timer part looks right to me, once you have made the fix of 50 seconds to 5 seconds that Prabhu pointed out. TimerEventProcessor will be executed every five seconds.

    As for the SQL part and updating the chart, I really can't say. It looks like it's okay, but I don't know much about SQL so I could be wrong. You will need the advice of an SQL expert if you are having trouble with that bit.

  • 2012년 5월 2일 수요일 오전 7:18
     
     

    Dear Ante,

                    Another thing I would like to how can I make this function TimerEventProcessor to be called immediately when the form is loaded rather wait for the interval to take place in the first loading? Another thing I remove the static keyword from this function else my chart is having reference problem is that ok? I am very confuse with this static? So about my chart whom should I post too?

  • 2012년 5월 2일 수요일 오후 11:53
     
      코드 있음

    Greetings Sukbir.

    I suggest taking the entire contents of TimerEventProcessor out and putting it in a new method called, say, UpdateChart. Then you can call this new method from TimerEventProcessor, and also when the form has loaded just before you start the timer.

            private  void TimerEventProcessor(Object myObject,
                                                    EventArgs myEventArgs)
            {
                UpadteChart();
            }
    
            private void UpdateChart()
            {
                // All the code that was in TimerEventProcessor goes in here.
                // Call this method once on first loading, then let it be called by TimerEventProcessor after that.
            }

    If you are having trouble understanding what static means, you are not alone. A lot of people have this trouble. It would take too long to give you a full tutorial on the subject here, but here's a quick summary.

    If you have a static variable in your form, it means that you can load many instances of that form and that variable will exist only once, shared by all of them, rather than each instance getting its own copy. So for example, if you wanted to load several forms at once and have them all be updated at exactly the same time every five seconds, then you could make the timer static. Then, whenever the timer ticks, it ticks for all the forms at once.

    On the other hand, if you only want one instance of your form to be loaded at a time, or if you want to load several instances but have them operate independently, leave the timer as not static, so that each form gets its own timer ticking at its own rate. I suspect that this is what you want.

    If you are having trouble with your chart, you should probably make another post in this forum which asks the relevant questions. I'm sure someone will know the answers.

  • 2012년 5월 3일 목요일 오전 8:13
     
     

    Dear Ante,

                    Thank you I have move to the updateChart function and everything works fine now. I think about the static looks like I have do more reading is ok I will do some more research and try to understand it better. About the chart yes I will start a new thread. Anyway thank you very much for your support and knowledge.