Search code examples
javaspringscheduled-tasksquartz-scheduler

Scheduler with custom fire time from DB


I need to write a scheduler (spring 4 application).
I have a number of fire times (start time) in DB. And I can create/delete them manually through UI. For each of this start time I need to invoke the method.

The reason why I can't use native @Scheduled is that:
1) my tasks is not repetitive (but it is not so big deal);
2) I need to handle start time manually. It shouldn't be hard-coded or set in properties. I need possibility to add new trigger in any time from UI without redeploying.

About Quartz Triggers, I'm not sure that it will match my problem. As I see it: I need to write some service that every few second will update all triggers accordingly to times from DB.

So, what is the best approach for my problem?


Solution

  • It's possible to update an existing trigger or replace it by another with quartz. So when you HMI update/add trigger then update/add it in your database and update/add in the scheduler.

    Updating an existing trigger:

    // retrieve the trigger
    Trigger oldTrigger = sched.getTrigger(triggerKey("oldTrigger", "group1");
    
    // obtain a builder that would produce the trigger
    TriggerBuilder tb = oldTrigger.getTriggerBuilder();
    
    // update the schedule associated with the builder, and build the new trigger
    // (other builder methods could be called, to change the trigger in any desired way)
    Trigger newTrigger = tb.withSchedule(simpleSchedule()
    .withIntervalInSeconds(10)
    .withRepeatCount(10)
    .build();
    //Reschedule
    sched.rescheduleJob(oldTrigger.getKey(), newTrigger);
    

    Replacing trigger:

    // Define a new Trigger
    Trigger trigger = newTrigger()
    .withIdentity("newTrigger", "group1")
    .startNow()
    .build();
    
    // tell the scheduler to remove the old trigger with the given key, and put the new one in its place
    sched.rescheduleJob(triggerKey("oldTrigger", "group1"), trigger);
    

    Those examples are from the quartz documentation.

    If you choose to use a JDBC JobStore don't write/update anything in directly in the quartz table.

    You shouldn't access to the JobStore (for any type of JobStore) you have to use the scheduler interface only.