play framework 2.6 定時任務,非同步排程任務的簡單使用
阿新 • • 發佈:2019-01-27
1、建立並啟用模組
public class ZTasksModule extends AbstractModule{ @Override protected void configure() { bind(CompositeImageTask.class).asEagerSingleton();//繫結CompositeImageTask任務 }
2、然後在application.conf中通過新增以下行來啟用該模組
play.modules.enabled += "tasks.ZTasksModule"
3、任務demo CompositeImageTask.java
public class CompositeImageTask{ private final ActorSystem actorSystem; private final ExecutionContext executionContext; @Inject public CompositeImageTask(ActorSystem actorSystem, ExecutionContext executionContext) { this.actorSystem = actorSystem; this.executionContext = executionContext; this.initialize(); } private void initialize() { this.actorSystem.scheduler().schedule( Duration.create(1, TimeUnit.MINUTES), // initialDelay 專案啟動後該任務多長時間執行 Duration.create(10, TimeUnit.MINUTES), // interval 該任務執行週期 () ->composite(), this.executionContext); }
//專案啟動後1分鐘執行該任務,然後每隔10分鐘執行一次
public void composite() {
/***任務邏輯***/
}
}