Is there other way to set long Timer Interval

I am making a program which has to check a data base once on every 30 or 60 minutes and display the results, if there are any, in the windows form interface. Of course, the other functions which the from provides access to, should still be usable while the data base check is being executed. To this end, I am using System.Timers.Timer which executes a method on a different thread from the UI one (If there is something wrong with using this approach, please feel free to comment on it). I wrote a small and simple program in order to test hot things work, only to notice that I cant really set the Interval to over ~ 1 minute ( I need 30 minutes to an hour). I came up with this solution:

public partial class Form1 : Form
{

    int s = 2;

    int counter = 1; //minutes counter

    System.Timers.Timer t;

    public Form1()
    {
        InitializeComponent();

        t = new System.Timers.Timer();
        t.Elapsed += timerElapsed;
        t.Interval = 60000;
        t.Start();
        listBox1.Items.Add(DateTime.Now.ToString());
    }


    //doing stuff on a worker thread
    public void timerElapsed(object sender, EventArgs e)
    {
        //check of 30 minutes have passed
        if (counter < 30)
        {
            //increment counter and leave method
            counter++;
            return;
        }
        else
        {
            //do the stuff
            s++;
            string result = s + "   " + DateTime.Now.ToString() + Thread.CurrentThread.ManagedThreadId.ToString();
            //pass the result to the form`s listbox
            Action action = () => listBox2.Items.Add(result);
            this.Invoke(action);
            //reset minutes counter
            counter = 0;
        }


    }

    //do other stuff to check if threadid`s are different
    //and if the threads work simultaneously
    private void button1_Click(object sender, EventArgs e)
    {
        for (int v = 0; v <= 100; v++)
        {

            string name = v + " " + Thread.CurrentThread.ManagedThreadId.ToString() +
                " " + DateTime.Now.ToString(); ;
            listBox1.Items.Add(name);
            Thread.Sleep(1000); //so the whole operation should take around 100 seconds
        }

    }
}

But this way, the Elapsed event is being raised and the timerElapsed method called once every minute, it seems kinda useless. Is there a way to actually set longer timer interval ?


Interval is in miliseconds,so it seems that you've set your interval for 60 seconds:

t.Interval = 60000; // 60 * 1000 (1 minute)

If you want to have 1 hour interval then you need to change your interval to:

t.Interval = 3600000; // 60 * 60 * 1000 (1 hour)
链接地址: http://www.djcxy.com/p/63018.html

上一篇: 一个定时器与三个定时器的性能

下一篇: 是否有其他方法来设置长时间间隔