如何在一周中的特定日期在Java Play Framework中运行akka调度程序?

时间:2015-04-21 12:43:34

标签: java playframework akka scheduler

我必须创建一个在一周的特定日期运行的调度程序。例如,我的调度程序应该在每个星期一晚上11:50运行。请帮我完成任务。

PS:我通过这些链接How to schedule task daily + onStart() in Play 2.0.4?建议使用cronJob表达式来计算下一个执行时间。有没有办法在默认情况下使用akka,即没有cronJob表达式?

2 个答案:

答案 0 :(得分:0)

schedule(initialDelay: Duration, frequency: Duration, receiver: ActorRef, message: Any)

您只需要计算所需的比例(分钟,小时,天)上的initialDelay。在您的情况下,您必须找到下周一之前的时间。这不是与Akka有关的问题,只是简单的Java:

//In minutes
private long timeToNextMonday(){
    Calendar now = Calendar.getInstance();
    now.set(Calendar.HOUR, 23);
    now.set(Calendar.MINUTE, 50);
    int weekday = now.get(Calendar.DAY_OF_WEEK);
    System.out.println(now.getTime());
    if (weekday != Calendar.MONDAY){
        // calculate how much to add
        // the 2 is the difference between Saturday and Monday
        int days = (Calendar.SATURDAY - weekday + 2) % 7;
        now.add(Calendar.DAY_OF_YEAR, days);
    }
    Date date = now.getTime();
    return (now.getTime().getTime() - System.currentTimeMillis())/(1000*60);
}

然后计划调用本身非常简单:

Akka.system().scheduler().schedule(
    Duration.create(timeToNextMonday, TimeUnit.MINUTES),
    Duration.create(7, TimeUnit.DAYS),
    actor, actorMessage,
    Akka.system().dispatcher(), null);

答案 1 :(得分:0)

public void onStart(Application application) {
  try{
      Duration.create(timeToNextMonday(), TimeUnit.MILLISECONDS),
      Duration.create(7, TimeUnit.DAYS),
      new Runnable() {
          @Override
          public void run() {
              JPA.withTransaction(new F.Callback0() {
                  @Override
                  public void invoke() throws Throwable {
                      System.out.println("Printing time : " + new Date());
                  }
              });
          }
      },
      Akka.system().dispatcher());
  }
  catch (Throwable t){
      HashMap<String,String> params = new HashMap<>();
      Logger.error("{}:params:{}", "error while starting cron for Historical TW questions", params, t);
  }
  super.onStart(application);
}
//In minutes
private long timeToNextMonday(){
    Calendar now = Calendar.getInstance();

    while (now.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        now.add(Calendar.DATE, 1);
    }

    now.set(Calendar.HOUR,11);
    now.set(Calendar.AM_PM,Calendar.PM);
    now.set(Calendar.MINUTE,50);
    now.set(Calendar.SECOND,00);
    now.set(Calendar.MILLISECOND,00);

    return now.getTime().getTime() - Calendar.getInstance().getTime().getTime();
}