Execute specified function every X seconds

后端 未结 4 1830
小鲜肉
小鲜肉 2020-11-27 15:02

I have a Windows Forms application written in C#. The following function checks whenever printer is online or not:

public void isonline()
{
    PrinterSettin         


        
相关标签:
4条回答
  • 2020-11-27 15:20

    The most beginner-friendly solution is:

    Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:

    private void wait_Tick(object sender, EventArgs e)
    {
        refreshText(); // Add the method you want to call here.
    }
    

    No need to worry about pasting it into the wrong code block or something like that.

    0 讨论(0)
  • 2020-11-27 15:23

    You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

    0 讨论(0)
  • 2020-11-27 15:30

    Threaded:

        /// <summary>
        /// Usage: var timer = SetIntervalThread(DoThis, 1000);
        /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
        /// </summary>
        /// <returns>Returns a timer object which can be disposed.</returns>
        public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
        {
            TimerStateManager state = new TimerStateManager();
            System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
            state.TimerObject = tmr;
            return tmr;
        }
    

    Regular

        /// <summary>
        /// Usage: var timer = SetInterval(DoThis, 1000);
        /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
        /// </summary>
        /// <returns>Returns a timer object which can be stopped and disposed.</returns>
        public static System.Timers.Timer SetInterval(Action Act, int Interval)
        {
            System.Timers.Timer tmr = new System.Timers.Timer();
            tmr.Elapsed += (sender, args) => Act();
            tmr.AutoReset = true;
            tmr.Interval = Interval;
            tmr.Start();
    
            return tmr;
        }
    
    0 讨论(0)
  • 2020-11-27 15:38

    Use System.Windows.Forms.Timer.

    private Timer timer1; 
    public void InitTimer()
    {
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 2000; // in miliseconds
        timer1.Start();
    }
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        isonline();
    }
    

    You can call InitTimer() in Form1_Load().

    0 讨论(0)
提交回复
热议问题