SpringBoot项目实现简单定时任务

利用@Scheduled注解和线程池实现
 

  @Scheduled(cron = "0 0 10 * * *") //十点开始执行
    public void add() {
        AtomicInteger count = new AtomicInteger();//计数器
        // 获取当前星期几
//            LocalTime currentTime = LocalTime.now();
        LocalDate today = LocalDate.now();

        // 如果是工作日,则执行任务
        if (isWeekday(today.getDayOfWeek()) ) {
            ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
            // 使用 scheduleAtFixedRate 方法,在每个工作日运行
            scheduledExecutorService.scheduleAtFixedRate(() -> {
                count.getAndIncrement();
                if (count.intValue()>10){
                    scheduledExecutorService.shutdown();
                    log.info("超过执行次数,关闭线程池");
                }else{
                    try {
                        
                            // 执行任务逻辑
                            log.info("任务执行");

                            scheduledExecutorService.shutdown();
                            log.info("关闭线程池");
                       
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


            }, 0, 10, TimeUnit.SECONDS); // 每10秒检查一次
        }else {
            log.info("非工作日不执行");
        }
    }

    private static boolean isWeekday(DayOfWeek dayOfWeek) {
        // 判断是否是工作日(周一到周五)
        return dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY;
    }

SpringBoot 项目在项目启动类上添加 @EnableScheduling 注解即可开启定时任务管理。 

@SpringBootApplication
@EnableScheduling  //开启定时任务
public class StoCrmApplication {

    public static void main(String[] args) {
        SpringApplication.run(StoCrmApplication.class, args);
    }

}

@Scheduled 比较官方一点的介绍 : 是 Spring 框架中用于定时调度任务的注解。它允许您将一个方法标记为一个定时任务,然后可以配置任务的执行时间间隔或 cron 表达式。这个注解通常与 Spring Boot 一起使用,以创建定时任务。

@Scheduled有四种属性,可供使用者对方法执行的时间进行配置 

  1. fixedRate:固定速率执行任务,单位为毫秒。每隔指定时间执行一次任务,不论任务执行时间的长短。
  2. fixedDelay:固定延迟执行任务,单位为毫秒。任务结束后,等待指定的时间间隔再执行下一次任务。
  3. initialDelay:首次执行任务前的延迟时间,单位为毫秒。用于指定第一次任务执行前的等待时间。
  4. cron:使用 cron 表达式配置任务触发时间,提供更灵活的定时配置选项。cron表达式允许你定义任务的执行时间规则,包括秒、分、时、日期等。
    例如,@Scheduled(cron = "0 0 2 * * ?") 表示每天凌晨2点执行。
    可通过在线生成cron表达式的工具:在线Cron表达式生成器 来生成自己想要的表达式。 

 默认情况下,Spring 定时任务是串行执行的。如果需要并发执行,可以考虑使用 @EnableAsync 注解开启异步支持,并在定时任务方法上添加 @Async 注解。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值