如何只停止一次定时器和一次 [英] how to stop timer andexecute only one time

查看:95
本文介绍了如何只停止一次定时器和一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友们,

创建一个应用程序,我使用计时器向客户端发送电子邮件文件。计时器工作正常他做我想要的完美工作但问题是它不能阻止它连续执行我希望计时器只执行一次我定义。我尝试使用timer.stop()方法,但是无法帮助我,请给我一些建议或帮助我粘贴我的代码



表单加载

hi friends,
iam creating one application where i sent email file to client side using timer . timer work fine he doing perfect work that i want but problem is that it cannot stop it continuously executed i want timer executed only one time which is i define. iam try timer.stop() method but cant help me please give some suggestion or help im paste here my code

for form load

System.Timers.Timer timer = new System.Timers.Timer();
             timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
             timer.Interval = 5000;
             timer.Start();





n计时器已经过去的事件我写了



n timer elapsed event i wrote

private void timer_Elapsed(object source, ElapsedEventArgs e)
     {


         System.Timers.Timer timer = new System.Timers.Timer();
         
         if ((DateTime.Now.DayOfWeek == DayOfWeek.Monday) && (DateTime.Now.Hour ==19) && (DateTime.Now.Minute == 46))
         {
             

             emailattachment();



         }
         timer.Stop();

推荐答案

将计时器对象保留为类的成员

在表单加载事件的类构造函数中创建计时器的实例

从您想要的方法启动计时器发送电子邮件,当滴答时间timer_Elapsed事件时,将调用您的emailAttachement方法



示例实现是

Keep the timer object as member to the class
Create the instance of the timer either in your class constructor of form load event
Start the timer from the method you want to send the e-mail, when time timer_Elapsed event is ticked your emailAttachement method will be called

sample implementation is
class Sample
{
  private Timer timer = null;
  
  public Sample
  {
    timer = new System.Timers.Timer();
    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    timer.Interval = 5000;
  }
  
  private DoProcess()
  {
    timer.Start();
  }
   
  private void timer_Elapsed(object source, ElapsedEventArgs e)
  {
//double check the logic here your emailattachment method will be called only when the condition is met and it stop the timer means this method wont get executed again until timer is started again
   if ((DateTime.Now.DayOfWeek == DayOfWeek.Monday) && (DateTime.Now.Hour ==19) && (DateTime.Now.Minute == 46))
    {
        emailattachment();
    }
   timer.Stop();
  }
}


这篇关于如何只停止一次定时器和一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆