Skip to content

Instantly share code, notes, and snippets.

@alexandru
Last active February 12, 2017 22:47
Show Gist options
  • Save alexandru/7f7d80e7e70e2d58c9d02b9cdc5f5a2a to your computer and use it in GitHub Desktop.
Save alexandru/7f7d80e7e70e2d58c9d02b9cdc5f5a2a to your computer and use it in GitHub Desktop.
import org.joda.time._
import monix.execution._
import monix.execution.Scheduler.Implicits.global
import java.util.concurrent.TimeUnit
import scala.util.control.NonFatal
def scheduleOncePerDay(time: LocalTime, now: DateTime = DateTime.now())(cb: () => Unit)
(implicit s: Scheduler): Cancelable = {
val nextTick = {
val next = now.toDateTime(DateTimeZone.UTC).withTime(time)
if (next.compareTo(now) <= 0) next.plusDays(1).getMillis else next.getMillis
}
s.scheduleOnce(nextTick - now.getMillis, TimeUnit.MILLISECONDS,
new Runnable {
def run(): Unit = {
try cb() catch {
case NonFatal(ex) => s.reportFailure(ex)
}
// Next please!
scheduleOncePerDay(time)(cb)(s)
}
})
}
@kevinmeredith
Copy link

kevinmeredith commented Feb 1, 2017

Thanks!

So my initial approach, namely scheduling a 'tick' every 55 minutes, and then checking if the getHourOfDay is 9, is wasteful? It's wasteful since I'm not, per your above example, precisely identifying when to fire the next tick, but I'm dumbly checking every 55 minutes's tick if it's the 9th hour of the day?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment