3

我目前正在使用 Play-Scala 框架和 akka actor 开发一个应用程序,以便在发生与数据库的 CRUD 操作时发送电子邮件。重启服务器时出现问题。

当 Play 框架重新启动或持久 akka 调度程序以及重新启动应用程序时,它将运行调度程序时重新加载 akka 调度程序的任何方式。例如,这是我的代码。

@Singleton
class SendEmailSaveDraftActor @Inject()(system: ActorSystem,
                                        config: Configuration,
                                        mailService: MailService)(implicit exec: ExecutionContext) extends Actor {

  val userSchedules: mutable.HashMap[String, Seq[Cancellable]] = mutable.HashMap()
  private val emailAdmin = config.getString("email.admin").getOrElse("")
  private val interval24Hours = config.getInt("batch.saveDarf24.extractIntervalHours").getOrElse(1)
  private val interval72Hours = config.getInt("batch.saveDarf72.extractIntervalHours").getOrElse(1)
  private val interval14Days = config.getInt("batch.saveDarf14.extractIntervalDays").getOrElse(1)

  def receive = {
    case s: SendEmailSaveDrafModel =>
      userSchedules.get(s.userName) match {
        case Some(schedules) =>
          schedules.map(_.cancel())
          userSchedules.update(s.userName, getSchedules(s))
        case None =>
          userSchedules += (s.userName -> getSchedules(s))
      }
    case userName: String =>
      userSchedules.get(userName) match {
        case Some(schedules) =>
          schedules.map(_.cancel())
        case None =>
      }
  }

  def getSchedules(s: SendEmailSaveDrafModel): Seq[Cancellable] = {
    val schedule1 = system.scheduler.scheduleOnce(5 minutes) {
      mailService Send EmailSaveDraft24Hours(to = Seq(s.to), bccEmails = Seq(emailAdmin),id = s.id, orderNo = s.orderNo,designId = s.designId)
    }
    val schedule2 = system.scheduler.scheduleOnce(10 minutes) {
      mailService Send EmailSaveDraft72Hours(to = Seq(s.to), bccEmails = Seq(emailAdmin),id = s.id, orderNo = s.orderNo,designId = s.designId)
    }
    val schedule3 = system.scheduler.scheduleOnce(15 minutes) {
      mailService Send EmailSaveDraft14Days(to = Seq(s.to), bccEmails = Seq(emailAdmin),id = s.id, orderNo = s.orderNo,designId = s.designId)
    }
    Seq(schedule1, schedule2, schedule3)
  }
}
4

1 回答 1

0

我正在使用 akka 调度程序,如下面的代码所示。

每个用户都可以登录到我的应用程序并可以为后台任务创建调度程序。我为此目的使用 Akka 调度程序。

public Cancellable buildScheduler(String actorName, SchedulerActorMessage message, long interval, TimeUnit timeUnit, long initialDelay, String actorMapKey) {

ActorRef daemonRef = actorSystem.actorOf(Props.create(SchedulerActor.class), actorName);
Cancellable cancellableActor = actorSystem.scheduler().schedule(FiniteDuration.apply(initialDelay, timeUnit),
        FiniteDuration.apply(interval, timeUnit), daemonRef, message,
        actorSystem.dispatcher(), ActorRef.noSender());
actorMap.put(actorMapKey, cancellableActor);
return cancellableActor;

}

我将必要的信息存储在数据库中,当应用程序启动时,我再次在全局类中盯着调度程序。

于 2018-10-09T14:45:45.780 回答