javajakarta-eejava-batch

Schedule a Cron like job in EJB


I have following EJB, which is scheduling 'MyJob' with fixed delay.

@Startup
@Singleton
public class Scheduler {

    static final long INITIAL_DELAY = 0;
    static final long PERIOD = 5;

    @Resource
    ManagedScheduledExecutorService scheduler;

    @PostConstruct
    public void init() {
        this.scheduler.scheduleWithFixedDelay(new MyJob(), INITIAL_DELAY, PERIOD, TimeUnit.SECONDS);
    }

}

I would like to schedule this job with cron like expression, how do I implement this without using Quartz or any other framework?

EDIT: To be more specific - I would like to have the cron like expression to be property driven. I would like to create the scheduler dynamically so that I don't have to create multiple beans for multiple batch jobs.


Solution

  • You can use @Schedule API:

    @Schedules({
                @Schedule(month = "5", dayOfMonth = "20-Last", minute = "0", hour = "8"),
                @Schedule(month = "6", dayOfMonth = "1-10", minute = "0", hour = "8")
        })
        private void plantTheCorn() {
            // Dig out the planter!!!
        }
    

    See this question and answers: Have an EJB schedule tasks with "crontab syntax"