spring如何做到隔一段时间后执行某个方法?

类似于JAVA的timer

用户发起结算后,3分钟后检查一下用户是否支付成功,若没有支付成功则将订单取消?

阅读 7.2k
5 个回答

那你就用timer啊,难道你spring框架不是用Java写代码吗

Spring支持定时任务。

在Spring boot中如果要使用schedule任务,那么可以这么写:

@Service
public class ScheduledTaskService{
     private static final SimpleDateFormat dateFormat = new SimpleDateFormat(“HH:mm:ss”);

     @Scheduled(fixedRate = 5000)
     public void reportCurrentTime(){
          System.out.println(“每隔五秒执行一次: “+dateFormat.format(new Date()));
     }

     @Scheduled(cron = “0 28 11 ? * *")
     public void fixTimeExecution(){
          System.out.println(“在指定时间: “+dateFormat.format(new Date())+”执行”);
     }
}

配置:

@Configuration
@EnableScheduling
public class TaskSchedulerConfig{
}

定时器 不仅可以做到每隔一段时间执行 还可以做到定点执行

spring有自己实现的task实现来执行,你也可以使用quartz

TaskScheduler.schedule(Runnable, Date)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题