希望仅在后台计时器达到阈值而不是每分钟时触发代码?

时间:2016-04-05 11:02:00

标签: c# linq timer backgroundworker

我试图在预约时间之前每3或5分钟发送一封电子邮件,但是某些原因代码每秒都会触发我只希望它在计时器到达threashold之前触发分配的时间,但我无法实现它。并且还可以使调试更容易。

protected void Page_Load(object sender, EventArgs e)  {
   Timer timer = new Timer();
   worker = new BackgroundWorker();
   worker.DoWork += worker_DoWork;
   timer.Elapsed += timer_Elapsed;
   timer.Interval = (1000) * (2);
   timer.Enabled = true;
   timer.Start();
}

private void timer_Elapsed(object sender, ElapsedEventArgs e)  {
   if (!worker.IsBusy)
      worker.RunWorkerAsync();
}

 private void worker_DoWork(object sender, DoWorkEventArgs e)  {
    //whatever You want the background thread to do...
    doReminders(3);
 }

 /// <summary>
 /// Does the reminders.
 /// sends out reminders based on the amount of minuties before a meeting
 /// </summary>
 protected void doReminders(int reminder)  {
    try  {
       List<ApertureDal.Appointment> _appointments = _dal.GetAppointmentsByReminderLength(reminder);

       _appointments.ForEach(x => {
           _dal.sendAppointmentEmails(x.ID, x.emailAddress, x.TimeCode, x.emailAddress, new Guid(Constants.calenderEmail), x.CustomerFirstName, x.CustomerLastName, x.managerName, x.preferedContactNumber, x.emailAddress, x.Start, x.End, x.managerId);
            });
    } catch (Exception ex) {}
}

编辑以显示GetAppointments功能

 /// <summary>
 /// Gets the appointments.
 /// </summary>
 /// <param name="reminderLength">Length of the reminder.</param>
 /// <returns></returns>
 public List<Appointment> GetAppointmentsByReminderLength(int reminderLength)
    {
        List<Appointment> list = new List<Appointment>();

        try
        {
            var q = from a in apertureNetEntities.Appointments //.Where(a => a.Start.Value.AddMinutes(-reminderLength) <= DateTime.Now)
                    select a;

            list = q.ToList();
        }
        catch (Exception ex)

        {
            string inner = string.Empty;
            if (ex.InnerException != null)
            {
                inner = ex.InnerException.ToString();
            }
            logger.Error("Error in List<Appointment> function GetAppointmentsByReminderLength " + ex.ToString() + " " + inner);
            return null;
        }

        return list;
  }

修改 目前它发送了98封电子邮件,即使我是数据库,他们只是我测试过的一条记录。

2 个答案:

答案 0 :(得分:1)

您将计时器间隔设置为(1000) * (2) - 即 - 两秒钟,因此计时器事件每2秒触发一次。

答案 1 :(得分:1)

如评论中所述:

问题在于,在此代码中无法识别电子邮件是否已发送。因此,如果预约到期,则会生成并发送电子邮件。 2秒后再次检查,仍然是指定的到期,所以它会一遍又一遍地发送电子邮件。

你的任命中需要有一些bool,你在_dal.sendAppointmentEmails中或之后设置为true,并且在_dal.GetAppointmentsByReminderLength中读取然后检查。如果任命已经设置为真,那么您不必发送电子邮件,如果它仍然是假的,您发送电子邮件并将bool设置为true等等。