示例
# ScheduledTaskService.java
package com.ln.myboot3.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private ScheduledTaskService() {
System.out.println("ScheduledTaskService Construct.......");
}
@Scheduled(fixedRate = 5000) //通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行
public void reportCurrentTime() {
System.out.println("每隔5秒执行一次 " + dateFormat.format(new Date()));
}
@Scheduled(cron = "0 07 20 ? * *") //使用cron属性可按照指定时间执行,本例指的是每天20点07分执行
//cron是UNIX和类UNIX(Linux)系统下的定时任务
public void fixTimeExecution() {
System.out.println("在指定时间 " + dateFormat.format(new Date()) + " 执行");
}
@Scheduled(cron = "0/10 * * * * ?")
public void init() {
this.prepare();
}
public void prepare() {
System.out.println("=== 每10s执行一次,now time:" + dateFormat.format(new Date()));
}
}
#配置 TaskScheduleConfig
package com.ln.myboot3.schedule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
@Configuration
@ComponentScan()
@EnableScheduling
public class TaskScheduleConfig {
@Bean
public TaskScheduler taskScheduler() {
return new ConcurrentTaskScheduler();
}
}
# 启动 Myboot3Application
package com.ln.myboot3;
import com.ln.myboot3.schedule.TaskScheduleConfig;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootApplication
public class Myboot3Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskScheduleConfig.class);
}
}
fixedDelay、fixedRate
fixedDelay控制方法执行的间隔时间,是以上一次方法执行结束开始算起,如上一次方法执行阻塞住了,那么直到上一次执行完,并间隔给定的时间后,执行下一次。
fixedRate是按照一定的速率执行,是从上一次方法执行开始的时间算起,如果上一次方法阻塞住了,下一次也是不会执行,但是在阻塞这段时间内累计应该执行的次数,当不再阻塞时,一下子把这些全部执行掉,而后再按照固定速率继续执行。
cron含义
[秒] [分] [时] [日] [月] [周] [年]
线上工具: https://cron.qqe2.com/