springboot 执行定时任务

1.maven

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

2.启动程序

@EnableScheduling

@SpringBootApplication

public class Application {

   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
   }
}
3.具体的任务类

@Component
@Profile({"test","prod"})
public class ScheduleTask {

    @Scheduled(cron = "0 10 4 1 * ?")
    public void doTask() {
      doSomeThing();
    }
}
4@Scheduled详解

@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行

@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行

@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次

@Scheduled(cron="*/5 * * * * *") :通过cron表达式定义规则。从后往前分别是年月日时分秒

更多例子:
"0 15 10 * * ? 2005"    2005年的每天早上10:15触发 
"0 * 14 * * ?"    每天从下午2点开始到2点59分每分钟一次触发 
"0 0/5 14 * * ?"    每天从下午2点开始到2:55分结束每5分钟一次触发 
"0 0/5 14,18 * * ?"    每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 
"0 0-5 14 * * ?"    每天14:00至14:05每分钟一次触发 
"0 10,44 14 ? 3 WED"    三月的每周三的14:10和14:44触发 
"0 15 10 ? * MON-FRI"    每个周一、周二、周三、周四、周五的10:15触发 

plus:
https://sanjay-f.github.io/2015/08/24/Spring%E7%9A%84%E4%B8%A4%E7%A7%8D%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6Scheduled%E5%92%8CAsync/
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java Spring Boot 中执行定时任务可以使用 Spring Framework 提供的 `@Scheduled` 注解来实现。以下是一些步骤: 1. 在你的 Spring Boot 应用程序中,创建一个带有 `@EnableScheduling` 注解的配置类。这个注解将启用 Spring 的定时任务功能。 ```java import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling public class AppConfig { } ``` 2. 创建一个带有定时任务方法的类,并使用 `@Scheduled` 注解来标记该方法。你可以设置定时任务执行时间表达式,决定任务在什么时候执行。 ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask { @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨执行 public void executeTask() { // 执行定时任务的逻辑 } } ``` 在上面的例子中,定时任务 `executeTask` 方法使用了 `cron` 表达式来定义每天凌晨执行的时间表达式。 3. 确保你的定时任务类被正确扫描并注入到 Spring 容器中。你可以在应用程序的主类上添加 `@ComponentScan` 注解,以确保扫描到你的定时任务类。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = "com.example") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 在上面的例子中,`@ComponentScan` 注解将扫描 `com.example` 包及其子包中的组件。 现在,你的定时任务应该在指定的时间执行了。确保你的应用程序已经启动,并检查日志输出以确认定时任务执行情况。 这是一个简单的示例,你可以根据自己的需求调整定时任务执行时间和逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值