I'm currently trying to create a firebase JobDispatcher within my android app that will start a job around 3am on a monday, regardless of when the job is created. I have seen examples of using Joda-Time, the Period class and TemporalAdjusters, but I am trying to support API levels 16 and up, so I need something that will work with those.
Currently I am building a new job with the following constraint (among others) .setTrigger(Trigger.executionWindow(secondsUntilMonday, secondsUntilMonday + toleranceInterval))
But I can't seem to find any examples of how to set my secondsUntilMonday to the number of seconds between when the method is called and around the next time 3am on a Monday rolls around.
Please help!
ZoneId here = ZoneId.of("America/Danmarkshavn");
ZonedDateTime now = ZonedDateTime.now(here);
ZonedDateTime nextMondayAtThree = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY))
.with(LocalTime.of(3, 0));
long secondsUntilMonday = ChronoUnit.SECONDS.between(now, nextMondayAtThree);
System.out.println(nextMondayAtThree);
System.out.println("Seconds: " + secondsUntilMonday);
When I ran this snippet just now, the output was:
2018-10-08T03:00Z[America/Danmarkshavn] Seconds: 147419
Please substitute your time zone since it probably isn’t America/Danmarkshavn.
I also invite you to compare not just the number of lines, but in particular the ease of reading with the answer using the outdated Calendar
class (don’t misunderstand me: if you wanted to use the Calendar
class, that would be a good answer; I just don’t think you will want to use the Calendar
class when you compare).
java.time
on Android API levels 16 and up?Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
and subpackages.java.time
.