Spring scheduling task - run only once

后端 未结 5 1017
我寻月下人不归
我寻月下人不归 2020-11-29 04:42

Is it possible to schedule Spring service method only once at exactly specified time? For example, current time is 2pm but when I hit the action button I want that my servic

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 05:14

    You can extend PeriodicTrigger as follows - it checks the lastCompletionTime: it will be null if the task has never run before. You can try variation of this if you want to run the task just once at some given time.

    class RunOnceTrigger extends PeriodicTrigger {
        public RunOnceTrigger(long period) {
            super(period);
            setInitialDelay(period);
        }
    
        @Override
        public Date nextExecutionTime(TriggerContext triggerContext) {
            if(triggerContext.lastCompletionTime() == null) {   // hasn't executed yet
                return super.nextExecutionTime(triggerContext);
            }
            return null;
        }
    }
    

提交回复
热议问题