SpringBoot定时任务

96 阅读1分钟

SpringBoot中使用注解@EnableScheduling和@Scheduled,实现定时任务功能。

  1. 在启动类中加入@EnableScheduling使注解@Scheduled生效。
package awen;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
 
@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 编写一个类,启动后自动执行@Scheduled,在控制台中可以看到每隔2秒输出一条信息。
package awen;
import java.util.Random;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TimeTest {
    // 定时器(每隔两秒调用一次)
//	@Scheduled(fixedRate = 2000)
	@Scheduled(cron = "0/2 * * * * ? ")
	private static void dataPoints() {
		Random random = new Random();
    	int rand = random.nextInt(100);
    	System.out.println(rand);
	}
}

Cron表达式解释 cron表达式 例如: 0/2 * * * * ?:每2秒执行一次 0 0 3 1 * ? : 表示在每月的1日的凌晨3点调整任务 0 0 10,15 ? :每天上午10点,下午3点 0 0 12 * * ? : 每天中午12点 0 0 8 ? * MON-FRI : 周一至周五的上午8:00触发

Cron表达式生成器:cron.qqe2.com