Spring Task 定时任务(cron的使用)
    		       		warning:
    		            这篇文章距离上次修改已过420天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring中使用@Scheduled注解配合cron表达式可以创建定时任务。以下是一个简单的例子:
- 首先,在Spring配置类上开启定时任务的支持:
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@EnableScheduling
public class ScheduledTaskConfig {
}- 创建定时任务类并使用@Scheduled注解,指定cron表达式:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
 
@Component
public class ScheduledTasks {
 
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
 
    @Scheduled(cron = "0 * * * * *") // 每分钟的每秒都会触发
    public void reportCurrentTime() {
        System.out.println("现在时间是:" + dateTimeFormatter.format(LocalDateTime.now()));
    }
}在这个例子中,reportCurrentTime方法会每分钟执行一次,每次执行时打印当前时间。
cron表达式的格式如下:
{秒} {分} {时} {日} {月} {星期} {年(可选)}每个字段可以包含特定的值,范围,列表,或者特殊字符如*(每一个可能的值),?(无指定值),/(步进),-(范围),和,(列表)。
评论已关闭