我们在项目中很多时候都会用到定时计划来执行任务. 比如说我们的订单(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>
希望对您有帮助,也希望留下一个赞鼓励下噢.