Springboot 开启定时任务

文章展示了如何在SpringBoot应用中配置和使用定时任务,包括启用定时任务注解,编写执行间隔5秒的简单任务以及处理支付超时和派送中状态的订单。通过@Scheduled注解配合Cron表达式,动态管理任务执行时间。
摘要由CSDN通过智能技术生成

资源:在线Cron表达式生成器

1、导入maven坐标 spring-context

        实际上在项目创建时已近自动引入

2、在启动类添加开启定时任务的注解 @EnableScheduling

package com.sky;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@EnableCaching //开启缓存的注解
@EnableScheduling //开启定时任务的注解
@Slf4j
public class SkyApplication {
    public static void main(String[] args) {
        SpringApplication.run(SkyApplication.class, args);
    }
}

 3、实现定时任务,每隔5秒打印一次时间

package com.sky.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/*自定义定时任务类*/
@Component
@Slf4j
public class MyTask {

    /*定时任务,每隔5秒触发一次*/
    @Scheduled(cron = "0/5 * * * * ?")
    public void executeTask(){
        log.info("定时任务开始 {}", new Date());
    }

}

4、下面直接copy一段项目中的应用场景

           业务逻辑:  每个一段时间,查看商品订单支付状态

        

package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/*
* 自定义定时任务,实现订单状态定时处理
* */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /*处理支付超时订单*/
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单:{}", new Date());

        //获取15分钟前的时间
        LocalDateTime time = LocalDateTime.now().minusMinutes(-15);

        // 查询15分钟前的待支付状态的订单
        List<Orders> orderList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        if(orderList != null && orderList.size() > 0){
            for (Orders order : orderList) {
                order.setStatus(Orders.CANCELLED);//修改订单状态为已取消
                order.setCancelReason("订单超时,自动取消");//取消原因
                order.setCancelTime(LocalDateTime.now());//取消时间
                orderMapper.update(order);//修改当前订单
            }
        }
    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单:{}", new Date());

        // 获取当前时间-1小时
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        /*获取一小时前的派送中订单*/
        List<Orders> orderList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if(orderList != null && orderList.size() > 0){
            for (Orders order : orderList) {
                order.setStatus(Orders.COMPLETED);//修改当前订单为已完成
                orderMapper.update(order);
            }
        }
    }

}

 

要在Spring Boot开启定时任务,你可以按照以下步骤进行操作: 1. 在启动类上使用`@EnableScheduling`注解来开启定时任务功能。例如: ```java @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 2. 在需要定时执行的方法上添加`@Scheduled`注解,并指定cron表达式来设置定时任务的触发时间。例如: ```java @Scheduled(cron = "*/6 * * * * ?") public void sayHello() { System.out.println("hello"); } ``` 上述示例中的`cron = "*/6 * * * * ?"`表示每隔6秒执行一次`sayHello()`方法。 这样,当你启动Spring Boot应用程序时,定时任务将自动开始执行。注意,定时任务的触发时间是按照cron表达式来设定的,根据你的需求进行调整即可。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot实现定时任务的三种方式](https://blog.csdn.net/m0_67401761/article/details/126114619)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Spring boot开启定时任务的三种方式](https://blog.csdn.net/qianlixiaomage/article/details/106599951)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [玩转SpringBoot定时任务详解](https://blog.csdn.net/weixin_30376163/article/details/97999503)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值