SpringBoot使用@Scheduled实现简单的定时任务

1.在启动类里面使用@EnableScheduling 注解开启功能,其中 @EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。

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


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

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

}

2.创建定时任务Java类

注意: 需要在定时任务的类上加上注释:@Component,在具体的定时任务方法上加上注释@Scheduled即可启动该定时任务。

@Component
public class TaskTest {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(cron = "0/3 * * * * ?")
    public static void taskTest(){
        System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
    }
}

执行结果:

 

cron表达式规则:https://www.cnblogs.com/dubhlinn/p/10740838.html

在线Cron表达式生成器:https://cron.qqe2.com/

好的,下面是一个使用 `@Scheduled` 注解实现定时任务Spring Boot 示例代码: 首先,在 Spring Boot 项目的 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 然后,在一个 Spring Boot 的 Java 类中添加以下代码: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) // 每隔 5 秒执行一次 public void task1() { System.out.println("Task1: " + System.currentTimeMillis()); } @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次 public void task2() { System.out.println("Task2: " + System.currentTimeMillis()); } } ``` 上面代码中,我们使用 `@Scheduled` 注解来实现两个定时任务,一个是每隔 5 秒执行一次,另一个是每分钟执行一次。 其中,`@Scheduled` 注解有两个常用的属性: - `fixedRate`:表示任务执行的间隔时间,单位为毫秒。 - `cron`:表示基于 Cron 表达式的定时任务配置,格式为 `second minute hour dayOfMonth month dayOfWeek year`。 最后,启动 Spring Boot 应用程序,即可看到定时任务在后台自动执行的输出结果。 注意:在 Spring Boot 应用程序中使用 `@Scheduled` 注解时,需要在应用程序主类上添加 `@EnableScheduling` 注解,以启用定时任务功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值