Question

I have a simple task: I need to run a process on the first day every 2 months even the server was down If the server will not down – the task is very easy:

ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
CronTrigger trigger = new CronTrigger("0 0 1 1 */2 ?");
scheduler.schedule(new Runnable() {
    @Override
    public void run() {
        // do the job
        job();
    }
}, trigger);

But what if the server was down and I run my job a month ago? In this case I want to execute my job on the beginning of the next month. I decided to store in the database when I executed the job last time:

private void job() {
// Store when the job was executed the last time
}

Now, when my server is launched, I need to start the trigger once again, but not immediately. I can easily calculate when I want to start the trigger, but unfortunately I can not find the appropriate function in ThreadPoolTaskScheduler. There is function that will allow to run task at start time periodically: public ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period)

Unfortunately, ThreadPoolTaskScheduler does not support public ScheduledFuture schedule(Runnable task, Date startTime, Trigger trigger) I implemented the functionality using additional scheduler.execute, but the question if it possible to do it using one schedule.

Était-ce utile?

La solution

You could use java.util.Timer to do that, and schdule the next TimerTask inside your TimerTask implementation.

If it has to be exactly two months you should schedule another TimerTask when the TimerTask starts, otherwise you could schedule it when the TimerTask ends.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top