在 SpringBoot 中使用 @EnableScheduling、@Scheduled 轻松实现定时任务

前言

之前接手师兄的 ITAEMBook 项目,里边就有类似王荣耀的 王者战报 功能,定期推送阅读信息给用户
现在实现定时任务的方法,很多人使用的是 quartz,而 SpringBoot 自带的两个注解就可以轻松搞定

定时任务

1、效果

这里写图片描述

2、代码
① 在 main 中开启定时任务的注解 @EnableScheduling

package com.cun;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling   //开启定时任务注解
@SpringBootApplication
public class AsMailTaskApplication {

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

②在 Service 中编写定时任务 @Scheduled

package com.cun.service;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class TaskService {

    /**
     * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
     * 例子:
     *  【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
     *  【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
     *  【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
     *  【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
     *  【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
     */
    @Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
    public void runTask(){
        System.out.println(new Date()+"发布王者战报");
    }
}

③ Maven 依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Spring Boot通过@EnableScheduling注解来开启定时任务的功能。下面是实现动态定时任务的步骤: 1. 首先,在你的Spring Boot应用的主类上添加@EnableScheduling注解,启用定时任务的支持。例如: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 2. 接下来,在需要执行定时任务的方法上添加@Scheduled注解,并设置定时任务的执行规则。例如,我们可以使用cron表达式来定义定时任务的执行时间。以下是一个示例: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyScheduledTask { @Scheduled(cron = "0 0/5 * * * *") // 每5分钟执行一次 public void doSomething() { // 定时任务要执行的操作 } } ``` 3. 现在,当应用启动后,定时任务会按照定义的规则自动执行。 如果你想在运行时动态地修改定时任务的执行规则,可以借助Spring的ScheduledTaskRegistrar类。可以在应用程序注入ScheduledTaskRegistrar对象,然后使用其方法来注册、取消和修改定时任务。这样你就可以实现动态的定时任务调度了。 希望这个回答对你有帮助!如果你还有其他问题,请随时提问。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT小村

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值