在 Spring Boot 中创建一个定时任务,可以通过以下步骤实现:

  1. 添加依赖:确保你的 pom.xml 中包含了 spring-boot-starter 依赖。
  2. 启用定时任务:在主应用程序类上添加 @EnableScheduling 注解。
  3. 创建定时任务类:使用 @Scheduled 注解定义任务方法。

以下是一个简单的示例:

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

@SpringBootApplication
@EnableScheduling
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@Component
class ScheduledTasks {

    @Scheduled(fixedRate = 5000) // 每5秒执行一次
    public void performTask() {
        System.out.println("定时任务执行时间:" + System.currentTimeMillis());
    }
}

在这个示例中,ScheduledTasks 类中的 performTask 方法会每5秒执行一次。

在 Spring Boot 中使用 Cron 表达式定义定时任务,可以通过 @Scheduled 注解的 cron 属性来实现。以下是一个示例:

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

@SpringBootApplication
@EnableScheduling
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@Component
class ScheduledTasks {

    @Scheduled(cron = "0 0 12 * * ?") // 每天中午12点执行
    public void performTask() {
        System.out.println("定时任务执行时间:" + System.currentTimeMillis());
    }
}

在这个示例中,@Scheduled(cron = "0 0 12 * * ?") 配置的 Cron 表达式会使 performTask 方法每天中午12点执行一次。