Springboot中定时任务的实现

1、定时任务在J2EE项目中经常会被用到,如自动取消订单、在指定的时间清空缓存等需求就需要定时任务来实现。定时任务的完成是靠轮询来实现的,所以存在一定的延时误差是合理的。springboot在实现定时任务的过程中相关的依赖已经在父依赖中被导入了,所以不需要导入额外的依赖。
2、SpringBoot中定时任务的实现分两步:(1、)定时任务的的实现;
(2、)创建调度表达式;
3、具体实现.
(1、)定时任务的的实现,其实就是你要通过定时器完成的业务逻辑:

@Scheduled(cron = "*/2 * * * * ?")
    public void serviceOrderTask() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YY:MM:DD hh:mm:ss");
        String formatDataStr = sdf.format(date);
        System.out.println("|_"+formatDataStr);
    }

(2、)配置调度表达式:
调度表达式的声明参考文章1.
调度表达式的声明参考文章2.

@Scheduled(cron = "*/2 * * * * ?")
    public void serviceOrderTask() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YY:MM:DD hh:mm:ss");
        String formatDataStr = sdf.format(date);
        System.out.println("|_"+formatDataStr);
    }

通过@Scheduled注解添加调度表达式.
4、需要注意的地方
在使用SpringBoot任务调度的时候,需要在启动类上添加注解@EnableScheduling。

package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值