在c#中使用定时器进行定期检查事件

本文关键字:检查 事件 定时器 | 更新日期: 2023-09-27 17:53:31

亲爱的兄弟,我是一个新人,我使用XML作为数据库,我想检索的方法,获取数据到我的标签控件在每10秒使用定时器控件在c#。

例如,获取数据和定时器控制的方法是:

private void timer1_Tick(object sender, EventArgs e)
        {
          //here how can I run this method at every 10 seconds  
                    ReturnUknowns();
        }

在c#中使用定时器进行定期检查事件

如果在创建计时器时遇到问题。如果要每10秒执行一次该函数,需要在创建计时器时指定计时周期。

Timer timer = new Timer(10000); // 10 seconds in miliseconds
timer.Tick += timer1_Tick;

和需要设置

的地方
timer.Start()
private void timer1_Tick(object sender, EventArgs e)
{
           //here how can I run this method at every 10 seconds  
           ReturnUknowns();
}

然后每隔10秒调用函数timer1_Tick()和其中指定的所有函数。计时器。根据项目的类型,Tick可能有不同的名称。

这是你可以测试删除注释从2秒间隔和位是有意义的理解的代码…

 public class Timer1
    {
        private static System.Timers.Timer aTimer;
        public static void Main()
        {
            // Normally, the timer is declared at the class level, 
            // so that it stays in scope as long as it is needed. 
            // If the timer is declared in a long-running method,   
            // KeepAlive must be used to prevent the JIT compiler  
            // from allowing aggressive garbage collection to occur  
            // before the method ends. You can experiment with this 
            // by commenting out the class-level declaration and  
            // uncommenting the declaration below; then uncomment 
            // the GC.KeepAlive(aTimer) at the end of the method. 
            //System.Timers.Timer aTimer; 
            // Create a timer with a ten second interval.
            aTimer = new System.Timers.Timer(10000);
            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            // Set the Interval to 2 seconds (2000 milliseconds).
            //aTimer.Interval = 2000;
            aTimer.Enabled = true;
            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();
            // If the timer is declared in a long-running method, use 
            // KeepAlive to prevent garbage collection from occurring 
            // before the method ends. 
            //GC.KeepAlive(aTimer);
        }
        // Specify what you want to happen when the Elapsed event is  
        // raised. 
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }
    }