admin 管理员组

文章数量: 1184232

1. 开启注解@EnableSchedling

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

2. 固定速率,按时触发

@Scheduled(fixedRate = 1000)
public void fixRate() throws InterruptedException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println("fixRate: " + sdf.format(new Date()));
    Thread.sleep(1000);
}

3. 固定间隔,等待前一次触发完毕后再执行

@Scheduled(fixedDelay = 1000)
public void fixDelay() throws InterruptedException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println("fixDelay: " + sdf.format(new Date()));
    Thread.sleep(1000);
}

 

当然,也支持cron表达式

@Scheduled(cron = "* * 21 * * ?")
public void cron() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println("cron: " + sdf.format(new Date()));
}

 

 

本文标签: schedule