简体   繁体   中英

EJB 3.0 TimerService - Run timer on 1st day of every month

In EJB 3.0 TimerService.createTimer(initialDuration, intervalDuration, TimerID) method is accepting only initialDuration and intervalDuration arguments.

The problem is I want to run timer on 1st of every month and I can not set my timer using cron expression like in EJB 3.1 TimerService .
Some workaround is like run on daily base and check the date inside @Timeout method if its '1st of month' but that is not appropriate way.

I went through many example/tutorials online but no luck. Is there any other way to implement this scenario?

I suggest the following approaches:

  • In the @Timeout method use JodaTime to calculate the next point-in-time. So every timer schedules the next call in its @Timeout method . This has the advantage that you are able to build an admin dialog that provides an overview of the scheduled timers in the system which you can't do if you just run the timer daily. I used this to implement a fairly complex, user-configurable timer configuration (Outlook style, ie something like "run this every two months on the third at 9:00 AM). Even with JodaTime, I ended up writing a lot of code, though. However, in your case it shouldn't be that complicated. Basically like

timerService.createTimer( new DateTime( System.currentTimeMillis()).plusMonths(1).withTimeAtStartOfDay().toDate(), null );

  • Abandon TimerService and use Quartz directly for scheduling. Then you can feed cron expressions directly into the API. Quartz generally integrates nicely with Java EE, even in complex clustered environments.
    try {
        Scheduler scheduler;
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();

        JobDetail job = new JobDetail("job name", "job group", (your class which will implement job interface).class);
        CronTrigger trigger = new CronTrigger("trigger name", "trigger group", "0 0 0 1 * ?");
        scheduler.scheduleJob(job, trigger);
    } catch (Exception e) {
        e.printStackTrace();
    }

Use above code it will run timer at 1st of every month.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM