首先要定义定时任务
@EnableScheduling
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
设置 cron
scheduler.thread.cron=0 0 10 * * ?
秒:表达式中第一个字段为 “0”,表示在每分钟的第 0 秒执行,即整分钟开始时执行。
分:第二个字段 “0”,表示每小时的第 0 分钟执行,即整点时执行。
时:第三个字段 “10”,代表每天的 10 点。
日:第四个字段 “”,表示在每个月的任意一天都满足条件。
月:第五个字段 “”,表示每个月都执行。
周:第六个字段 “?”,表示不关心是星期几,即不管是星期几都会在每天上午 10 点执行任务,因为已经通过前面的 “日” 和 “月” 字段确定了每天执行,所以星期字段就不需要再做限制。
创建线程
public class GetStockDataThread
{
@PostConstruct
public void init() {
System.out.println("初始化线程");
}
@Scheduled(cron = "${scheduler.thread.getstocklist.cron}")
public void task2() {
System.out.println("定时任务2执行,线程:" + Thread.currentThread().getName());
}
}