Play 2.5 - 在一天的特定时间运行Java方法(cron)

时间:2017-02-09 14:53:37

标签: java scala cron playframework-2.0 sbt

我正在开发一款需要在每天正午,下午2点,下午4点自主运行方法的Play 2.5应用。

到目前为止,我已经关注了another answer on here,这让我大部分都得到了。 application.conf文件已更新,以查看Module文件,该文件正确绑定到OnStartup()方法。

我认为问题与OnStartup()方法中的代码有关,我已经包含了下面的代码 - 这是在一天的特定时间运行某些东西的正确方法吗?

package controllers;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import java.util.Calendar;


@Singleton
public class OnStartup {

    @Inject
    public OnStartup() {

        Calendar cal = Calendar.getInstance();

        String hour = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
        String minute = String.valueOf(cal.get(Calendar.MINUTE));

        String dateTime = hour + ":" + minute;
        String time = "12:00";
        String time1 = "14:00";
        String time2 = "16:00";

        if (dateTime.equals(time) || dateTime.equals(time1) || dateTime.equals(time2)){
            System.out.print(dateTime);
            myAmazingClass.doSomethingWonderful();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

根据您的方法,您需要三件事,模块,演员和调度程序。

第1步:创建演员

import akka.actor.UntypedActor;
import play.Logger;

public class DoSomethingActor extends UntypedActor{

    @Override
    public void onReceive(final Object message) throws Throwable {
        Logger.info("Write your crone task or simply call your method here that perform your task"+message);

    }

}

步骤2:创建调度程序

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Cancellable;
import scala.concurrent.duration.Duration;

@Singleton
public class DoSomethingScheduler {

    @Inject
    public DoSomethingScheduler(final ActorSystem system,
            @Named("do-something-actor") final ActorRef doSomethingActor) {
        final Cancellable scheduler;
        final int timeDelayFromAppStart = 0;
        final int timeGapInSeconds = 1; //Here you provide the time delay for every run
        system.scheduler().schedule(
                Duration.create(timeDelayFromAppStart, TimeUnit.MILLISECONDS), //Initial delay when system start
                Duration.create(timeGapInSeconds, TimeUnit.SECONDS),     //Frequency delay for next run
                doSomethingActor,
                "message for onreceive method of doSomethingActor",
                system.dispatcher(),
                null);
    }
}

步骤3:使用模块绑定调度程序和actor。

import com.google.inject.AbstractModule;

import play.libs.akka.AkkaGuiceSupport;

public class SchedulerModule extends AbstractModule implements AkkaGuiceSupport{

    @Override
    protected void configure() {
        this.bindActor(DoSomethingActor.class, "do-something-actor");
        this.bind(DoSomethingScheduler.class).asEagerSingleton();
    }

}

步骤4:在aaplication.conf中配置模块

play.modules.enabled += "com.rits.modules.SchedulerModule"

确保无需担心onStart模块像往常一样离开,此模块仅用于调度任务的目的。