Scala定时任务启动例子
Scala代码
package com.scala.testimport java.time.LocalDateTime
import java.util.concurrent.Executors
import scala.concurrent.duration._
import org.apache.spark.sql.SparkSessionobject TimingTaskTest {def main(args: Array[String]): Unit = {val spark = SparkSession.builder().appName("TimingTaskTest").master("local[*]") // Replace with your Spark cluster configuration.getOrCreate()val scheduler = Executors.newScheduledThreadPool(5)// Define the task to be executedval task = new Runnable {def run(): Unit = {// Print the current timeval currentTime = LocalDateTime.now().toLocalTimeprintln(s"定时任务:Current time: $currentTime")// Add your logic here to perform the daily job// ...}}// Calculate the initial delay until the next 16:40:00val initialDelay = {val now = LocalDateTime.now()val targetTime = now.withHour(18).withMinute(36).withSecond(0)val delay = java.time.Duration.between(now, targetTime).toMillis.millisif (delay > 0.millis) delay else 1.day + delay}// Schedule the task to run every day at 16:40:00scheduler.scheduleAtFixedRate(task, initialDelay.toMillis, 1.day.toMillis, java.util.concurrent.TimeUnit.MILLISECONDS)println("End")}
}
控制台输出:
End
定时任务:Current time: 18:36:00.254