Spring计划任务/任务调度,固定时间循环,或者指定时间执行计划任务

我们在项目中很多时候都会用到定时计划来执行任务. 比如说我们的订单(30分钟内未付款就需要取消订单)这时候我们就需要定时任务来执行了.
我们可以直接利用spring自带的定时计划 @Scheduler
下面是业务执行类
TaskSchedulerDemo .class

package com.clx.demo.service;

import cn.hutool.core.date.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @author clx
 * 执行任务
 */
@Service
public class TaskSchedulerDemo {

    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTime(){
        //TODO 固定时间循环任务
        System.out.println("每隔5秒执行一次"+ DateUtil.now());
    }

    @Scheduled(cron = "0 24 14 ? * *")
    public void fixTimeExecution() {
        //TODO 执行指定任务
        System.out.println("在指定时间执行"+DateUtil.now()+"任务");
    }
    /**
     * 每隔5秒执行一次2020-05-05 14:23:48
     * 每隔5秒执行一次2020-05-05 14:23:53
     * 每隔5秒执行一次2020-05-05 14:23:58
     * 在指定时间执行2020-05-05 14:24:00任务
     */
    
}

配置类

package com.clx.demo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @author clx
 */
@Configuration
//扫描我们的server类 就是扫描路径com.clx.demo.service下的所有计划类;
@ComponentScan("com.clx.elasticsearchdemo.service")
@EnableScheduling //开启计划任务
public class TaskSchedulerConfig {

}

好的计划任务就这样简单的完成了,我们来看下效果

每隔5秒执行一次2020-05-05 14:23:48
每隔5秒执行一次2020-05-05 14:23:53
每隔5秒执行一次2020-05-05 14:23:58
在指定时间执行2020-05-05 14:24:00任务

在这边也介绍下我使用的工具类,是HuTool工具类.第三方封装的.非常使用.里面内容非常丰富,推荐您使用. 下面是最新依赖,
官方地址https://www.hutool.cn
GitHub :https://github.com/looly/hutool

		<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.2</version>
        </dependency>

希望对您有帮助,也希望留下一个赞鼓励下噢.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值