springBoot中的定时任务实现代码详解

     今天新接了一个需求,需要有一个定时任务,在工作日内,每十分钟调用存过。现在就自己写一个简单demo用于后续代码引用。

1、基于注解创建定时任务

     cron表达式说明可以参考:https://blog.csdn.net/m0_37179470/article/details/81271607

代码:

@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    //3.添加定时任务
    @Scheduled(cron = "0 0/10 * * * ?")
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

这样可以实现每隔10分钟,就执行一次定时任务。

而如果需要在工作时间内的每个十分钟进行调用定时任务,就需要指定时间。

我修改了cron表达式为:

cron = 0 0/10 8,9,10,11,14,15,16,17,18 * * ?

感觉要计算工作日太麻烦了,所以费劲千辛万苦,从github大佬那找了个插件。该插件作者已经把项目上传到中央仓库,可自行引用下载。maven引用如下:

	<dependency>
			<groupId>com.icexxx</groupId>
			<artifactId>iceworkday</artifactId>
			<version>2.0.2.0</version>
		</dependency>

使用方法及源码可以去此github上自行下载或者搜索。

链接入口奉上:https://github.com/iceenongli/iceworkday

写了个main方法进行验证改插件的用法。如下:

import com.iceyyy.workday.WorkUtils;

 public static void main(String[] args) {
        SimpleDateFormat format =new SimpleDateFormat("yMMdd");//根据作者写的源码,此项目需要设置成如下格式日期
        String date =format.format(new Date());//获取当前规定格式日期字符串
        System.out.println(date);
        System.out.println( WorkUtils.isWorkendDay(date));//判断是不是节假日,如果不是节假日会返回false,是节假日会返回true
    }

自此,可以输出出完整的定时任务的demo,仅供参考,后续如果有改动会持续更新:

import com.iceyyy.workday.WorkUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Classname SaticScheduleTask
 * @Description: 定时任务demo类  工作日(剔除法定假日),工作时间(8-12 2-6)每十分钟对订单进行一次轮训
 * @since 2020-03-18
 */
@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    //3.添加定时任务
    @Scheduled(cron = "0 0/10 8,9,10,11,14,15,16,17,18 * * ?")
    private void configureTasks() {
        //每十分钟进入此方法,取得当前时间。按照约定格式进行封装。
        SimpleDateFormat format =new SimpleDateFormat("yMMdd");
        String date =format.format(new Date());
        if(!WorkUtils.isWorkendDay(date)){//如果是工作日
            System.out.println("调用存过~");
        }
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }


}

测试结果按照预期运行:

至此完成定时任务demo的编写~

谢谢观看~

Keep your chin up, someday there will be happiness again.
抬起头来,幸福快乐总有一天会重临。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值