在不同时区的特定时间安排电子邮件

Ton*_*ark 4 c# asp.net-mvc timezone datetime

根据用户时区在上午 11.30 向用户发送每日摘要电子邮件的优化方式,

向用户发送电子邮件工作正常,但要在特定时间及其时区发送?

我拥有的

UserProfile with timezoneid,emailid
Dynamic daily email content
Run Code Online (Sandbox Code Playgroud)

目前我正在使用控制台应用程序在 UTC 时间上午 11.30 发送,

但如何处理多个时区?有人能帮我吗?

CSL*_*CSL 5

我通过作为计划任务运行的控制台应用程序实现了此类功能,该应用程序每 X 分钟轮询一次数据库以查看是否需要发送任何电子邮件。

我假设UserProfile是一个保存您的用户列表的数据库表。

为了实现此目的,我将在此表中添加一个附加列来存储上次发送的日期/时间。这是必要的,因为当您开始按时区发送时,您显然无法每天在同一时间发送所有电子邮件,并且需要跟踪哪些电子邮件已发送或哪些电子邮件需要发送。

另外,由于此类任务的性质,如果由于某种原因失败或未运行,您可能需要“赶上”,即发送任何错过的电子邮件(尽管这可能不是您的要求)也可以通过检查最后发送的列来实现。

假设您想在当地时间上午 11:30(或接近上午 11:30)向每个用户发送电子邮件,以下代码应该有效:

IList<UserProfile> users = // Load user profile from database

foreach(UserProfile user in user){

    // Work out this users local time by converting UTC to their local TimeZone
    DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, user.TimeZoneId);

    if(user.LastSent.HasValue && user.LastSent.Value.Date == localDateTime.Date){
       // Already sent an email today
       continue;
    }

    if(localDateTime.Hour >= 11 && localDateTime.Minute >= 30){
       // After 11:30am so send email (this could be much later than 11:30 depending on other factors)
       if(SendEmail(user.EmailId)){
           // Update last sent that must be in local time
           user.LastSent = Converter.ToLocalTime(DateTime.UtcNow, user.TimeZoneId);

           // Save User entity
           // UserPersistence.Save(user);
       }

    }

}
Run Code Online (Sandbox Code Playgroud)

现在作为警告,只要代码正在运行并且取决于用户量/发送每封电子邮件的延迟等,上面的代码将在到达 11:30 后立即发送电子邮件。如果您有每 5 分钟运行一次的计划任务那么显然准确度将精确到 5 分钟,因此可能要到上午 11:35 才会发送。如果您想要更高的准确性,您可以更频繁地运行计划任务。另一个考虑因素是,如果同一时区有 30000 个用户,那么发送大量电子邮件的延迟自然意味着并非所有电子邮件都可以在上午 11:30 准确发送。

也就是说,上面的代码应该让您朝着正确的方向开始。