定时任务 - 构建定时任务task

@Component
public class OrderJob {

    @Autowired
    private OrderService orderService;

    /**
     * 使用定时任务关闭超期未支付订单,会存在的弊端:
     * 1. 会有时间差,程序不严谨
     *      10:39下单,11:00检查不足1小时,12:00检查,超过1小时多余39分钟
     * 2. 不支持集群
     *      单机没毛病,使用集群后,就会有多个定时任务
     *      解决方案:只使用一台计算机节点,单独用来运行所有的定时任务
     * 3. 会对数据库全表搜索,及其影响数据库性能:select * from order where orderStatus = 10;
     * 定时任务,仅仅只适用于小型轻量级项目,传统项目
     *
     * 后续课程会涉及到消息队列:MQ-> RabbitMQ, RocketMQ, Kafka, ZeroMQ...
     *      延时任务(队列)
     *      10:12分下单的,未付款(10)状态,11:12分检查,如果当前状态还是10,则直接关闭订单即可
     */

//    @Scheduled(cron = "0/3 * * * * ?")
//    @Scheduled(cron = "0 0 0/1 * * ?")
    public void autoCloseOrder() {
        orderService.closeOrder();
        System.out.println("执行定时任务,当前时间为:"
                + DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN));
    }

}
/**
 * A cron-like expression, extending the usual UN*X definition to include triggers
 * on the second as well as minute, hour, day of month, month and day of week.
 * <p>E.g. {@code "0 * * * * MON-FRI"} means once per minute on weekdays
 * (at the top of the minute - the 0th second).
 * <p>The special value {@link #CRON_DISABLED "-"} indicates a disabled cron trigger,
 * primarily meant for externally specified values resolved by a ${...} placeholder.
 * @return an expression that can be parsed to a cron schedule
 * @see org.springframework.scheduling.support.CronSequenceGenerator
 */
String cron() default "";
@EnableScheduling       // 开启定时任务

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A:Spring Boot和Mybatis-plus都是用于开发Java应用程序的工具。Spring Boot提供了方便的快速构建基于Spring框架的应用程序的功能,而Mybatis-plus则提供了更简单、更高效的操作数据库的方式。 要基于Mybatis-plus实现定时任务,可以使用Spring框架提供的@Scheduled注解来定时执行任务,并在任务中使用Mybatis-plus提供的工具类操作数据库。 具体实现步骤如下: 1. 在Spring Boot项目中引入Mybatis-plus的依赖。 2. 创建一个定时任务类,使用@Scheduled注解来指定任务执行的时间。在类中注入Mybatis-plus提供的Mapper对象,用于执行数据库操作。 3. 在定时任务的方法中编写任务执行的代码逻辑,可以使用Mybatis-plus提供的CRUD操作来操作数据库。 4. 在配置文件中配置定时任务的线程池等相关参数。 示例代码如下: ```java @Component public class MyTask { @Autowired private MyMapper myMapper; @Scheduled(cron = "0 0 0 * * ?") public void task() { List<MyEntity> list = myMapper.selectList(null); //...执行任务逻辑 } } @Service public interface MyMapper extends BaseMapper<MyEntity> { List<MyEntity> selectList(); } ``` 在以上示例代码中,MyEntity类表示数据库中的实体对象,MyMapper接口继承自Mybatis-plus的BaseMapper接口,用于操作数据库。定时任务逻辑通过@Scheduled注解指定执行时间,并注入了MyMapper对象用于执行数据库操作。 需要注意的是,在定时任务中尽量避免使用阻塞式的代码,以免影响其他任务的正常执行。同时,要根据实际情况灵活选择任务执行的时间和频率,以达到最佳效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值