Home > OS >  How to configure SingleThreadScheduledExecutor to run a job every 15mins between 8am to 10am and the
How to configure SingleThreadScheduledExecutor to run a job every 15mins between 8am to 10am and the

Time:07-08

I need some assistance on how to implement the SingleThreadScheduledExecutor to run the job every 15mins between 8 am to 10 am UK time and then every 1hr throughout the day.

Currently, I have the following Scala code -

val pollingExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("MyTestScheduledThread"))

pollingExecutor.scheduleWithFixedDelay(new MyRunnableJob(), 0, 15, TimeUnit.MINUTES)

CodePudding user response:

I would make a wrapper around the job that takes care of scheduling:

class ScheduledRun(
   job: Runnable, 
   scheduler: ScheduledExecutorService
 )(delay: => Duration) extends Runnable {
   def schedule(): Unit = delay match {
     case d: FiniteDuration => scheduler.schedule(this, d.toMillis, MILLISECONDS)
     case _ => 
   }
   def run(): Unit = {
     job.run()
     schedule()
   }
}

And then you can just do:

new ScheduledRun(myRunnableJob, pollingExecutor)(
   if (isMorningInUK) 15 minutes else 1 hour
).schedule
  • Related