Fork me on GitHub

Scheduler

Introduction

Sometimes you have to do some tasks in a scheduled way. Let's say every 24 hours.

To make that happen in Ninja you need two things

  • An method annotated of class X with @Schedule
  • X being bound explicitly by Guice

The class and binding

The class and method then looks like:

@Singleton
public class ScheduledAction {


    @Schedule(delay = 60, initialDelay = 5, timeUnit = TimeUnit.SECONDS)
    public void doStuffEach60Seconds() {
        // do stuff
    }
}

Don't forget to bind the class explicitly inside conf/Module.java

public class Module extends AbstractModule {

    protected void configure() {

        bind(ScheduledAction.class);

    }
}

By that Ninja will execute method doStuffEach60Seconds each - well - 60 seconds.

CRON expression

Sometimes you need to schedule tasks in an advanced way and without depending on when the application has started. For this you can use a CRON expression.

The format of the CRON expression must be : second, minute, hour, day of month, month and day of week.

Unit Value Step Value Extra Information
Second 0 - 59 1 - 60
Minute 0 - 59 1 - 60
Hour 0 - 23 1 - 24
Day of Month 0 - 31 1 - 32
Month 0 - 12 1 - 13
Day of Week 0 - 6 1 - 7 0: Sunday, 1: Monday, ..., 6: Saturday
@Singleton
public class ScheduledAction {


    @Schedule(cron = "0 */5 * * * *")
    public void doStuffEach5minutes() {
        // do stuff
    }

    @Schedule(cron = "0 0 23 * * *", cronZone = "Europe/Paris")
    public void doStuffEachDayAt23HourEuropeParis() {
        // do stuff
    }

    @Schedule(cron = "0 30 2,14 * * 1-5")
    public void doStuffTwiceADayFromMondayToFriday() {
        // do stuff
    }
}