[Play 2.6 - Java] Schedule at the same hour each day

I’ve to schedule a check that sends an email at the same hour each day. Is there a way to do that in Play?

Create an Akka Actor using the ActorSystem, and use its scheduler.

final ActorRef actor = actorSystem.actorOf(<props>);
actorSystem.scheduler().schedule(Duration.Zero, new Duration(86400, TimeUnit.SECONDS, actor.....)

If your environment is load balanced one option is to create a AWS Lambda (easy to schedule) that hits a url to trigger the event.

1 Like

Ok, but when start the scheduler? I tried the following

this.actorSystem.scheduler().schedule(
                Duration.create(10, TimeUnit.SECONDS), // initialDelay
                Duration.create(1, TimeUnit.DAYS), // interval
                () -> checkForRefill(),
                this.executionContext
        );

but it starts now and the first trigger is next day at the same hour. But if I want to start at 1:00AM (e.g.) I’ve to start Play at 1:00AM.

My environment isn’t load balanced. Sorry.

You would need to calculate the time diff between 1.00 AM and the time the scheduler executes first time in seconds and that would be your initial delay represented as FiniteDuration.

Thanks, if I do:

private void initialize() {
        LocalDateTime now  = LocalDateTime.now();
        Integer year = now.getYear();
        Integer month = now.getMonthValue();
        Integer day = now.getDayOfMonth();
        LocalDateTime tomorrow = LocalDateTime.of(year, month, day+1,1, 01,00 );
        Long hours = now.until(tomorrow, ChronoUnit.HOURS);
        this.actorSystem.scheduler().schedule(
                Duration.create(10, TimeUnit.SECONDS), // initialDelay
                Duration.create(1, TimeUnit.DAYS), // interval
                () -> checkForRefill(),
                this.executionContext
        );
    }

in hours I’ve the diff time, where I’ve to put it, in interval or initial delay?

Initial Delay. The interval is 24 hours anyway right? So it the initial execution happens at 1.00 AM, subseqeunt executions would happen at the same time every day.

Ok, thanks.

Could you please share an example for creating scheduled task? I’m stuck in this.
Thank you so much!

Hey @khoatran,

There are examples on our docs here: https://www.playframework.com/documentation/2.7.x/ScheduledTasks

Best.

2 Likes

You are right!