Is Spring's built in Scheduler persistent.?

前端 未结 2 756
花落未央
花落未央 2021-01-02 09:36

I have run into a case where I have to use a persistent Scheduler, since I have a web application that can crash or close due to some problems and might los

相关标签:
2条回答
  • 2021-01-02 09:44

    @Schedule has nothing to do with the actual executor. The default java executors aren't persistent (maybe there are some app-server specific ones that are), if you want persistence you have to use Quartz for job execution.

    0 讨论(0)
  • 2021-01-02 09:57
    1. No, Spring's @Schedule-annotation will typically only instruct Spring at what times a certain task should be scheduled to run within the current VM. As far as I know there is not a context for the execution either. The schedule is static.

    2. I had a similar requirement and created db-scheduler (https://github.com/kagkarlsson/db-scheduler), a simple, persistent and cluster-friendly scheduler. It stores the next execution-time in the database, and triggers execution once it is reached.

    A very simple example for a RecurringTask without context could look like this:

    final RecurringTask myDailyTask = ComposableTask.recurringTask("my-daily-task", Schedules.daily(LocalTime.of(8, 0)),
                    () -> System.out.println("Executed!"));
    
    final Scheduler scheduler = Scheduler
            .create(dataSource)
            .startTasks(myDailyTask)
            .threads(5)
            .build();
    
    scheduler.start();
    

    It will execute the task named my-daily-task at 08:00 every day. It will be scheduled in the database when the scheduler is first started, unless it already exists in the database.

    If you want to schedule an ad-hoc task some time in the future with context, you can use the OneTimeTask:

        final OneTimeTask oneTimeTask = ComposableTask.onetimeTask("my-onetime-task",
                (taskInstance, context) -> System.out.println("One-time task with identifier "+taskInstance.getId()+" executed!"));
    
        scheduler.scheduleForExecution(LocalDateTime.now().plusDays(1), oneTimeTask.instance("1001"));
    
    1. See the example above. Any number of tasks can be scheduled, as long as task-name and instanceIdentifier is unique.
    0 讨论(0)
提交回复
热议问题