回到主页

Scala定时任务配置使用

· scala

通常定时任务以当前部署时间为基础触发时间。

如果需要每次在特定时间(如半夜),可以使用方便限定。

def delayToMiddleNight(plusMinutes: Int = 0) = { val nw = OffsetDateTime.now(SvrZoneId) val nd = nw.plusDays(1) val mn = OffsetDateTime.of(nd.getYear, nd.getMonthValue, nd.getDayOfMonth, 0, 0, 0, 0, SvrZoneOffset) plusMinutes * 60 + mn.toEpochSecond - nw.toEpochSecond }   具体使用的案例如下:
17:23

//代码展示

import java.time.{OffsetDateTime, ZoneId, ZoneOffset}
import javax.inject.{Inject, Singleton}

import akka.actor.ActorSystem
import play.api.{Configuration, Logger}
import play.api.inject.ApplicationLifecycle
import play.api.libs.json.{JsValue, Json}
import play.api.libs.ws.{WSAuthScheme, WSClient, WSRequest}

import scala.concurrent._
import scala.concurrent.duration._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import utils.ApiUtil._

@Singleton
class HeartBeatService @Inject() (actorSystem: ActorSystem, lifecycle: ApplicationLifecycle, val configuration: Configuration,
                                  val repoService: RepoService,val encryptService: EncryptService) {
  private val logger = Logger(this.getClass)

  val SvrZoneId = ZoneId.of("Asia/Shanghai")
  val SvrZoneOffset = ZoneOffset.ofHours(8)

  def delayToMiddleNight(plusMinutes: Int = 0) = {
    val nw = OffsetDateTime.now(SvrZoneId)
    val nd = nw.plusDays(1)
    val mn = OffsetDateTime.of(nd.getYear, nd.getMonthValue, nd.getDayOfMonth, 0, 0, 0, 0, SvrZoneOffset)
    plusMinutes * 60 + mn.toEpochSecond - nw.toEpochSecond
  }

  val delay1 = delayToMiddleNight(600).second
  val delay2 = delayToMiddleNight(15).second

  actorSystem.scheduler.schedule(delay1, 24.hour) {
    encryptService.remind()
    println("执行短信发送完毕")
  }



  lifecycle.addStopHook{ () =>
    Future.successful(actorSystem.terminate())
  }


  actorSystem.scheduler.schedule(delay2, 24.hour) {             //人员同步
    encryptService.empSynch()
  }

}
       

注意点:

必须先module中启动定时服务。

bind(classOf[HeartBeatService]).asEagerSingleton() 具体完整代码如下:
17:23

//代码展示

class Module extends AbstractModule {

  override def configure() = {
    // Use the system clock as the default implementation of Clock
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
    // Ask Guice to create an instance of ApplicationTimer when the
    // application starts.
    bind(classOf[ApplicationTimer]).asEagerSingleton()
    // Set AtomicCounter as the implementation for Counter.
    bind(classOf[Counter]).to(classOf[AtomicCounter])

    bind(classOf[HeartBeatService]).asEagerSingleton()
  }

}