spring boot 中 pom 文件配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
spring boot 啓動類
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
定時任務
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
@Component
public class ScheduledService {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);
//單線程定時任務
@Scheduled(cron="0 0/1 * * * ?")
public void one() {
// 間隔2分鐘,執行任務
Thread current = Thread.currentThread();
logger.info("ScheduledTest.executeFileDownLoadTask 定時任務1:"+current.getId()+ ",name:"+current.getName());
}
@Scheduled(cron="0 0/2 * * * ?")
public void two() {
// 間隔2分鐘,執行任務
Thread current = Thread.currentThread();
logger.info("ScheduledTest.executeFileDownLoadTask 定時任務1:"+current.getId()+ ",name:"+current.getName());
}
}
cron表達式詳解
0 0/2 * * * ?
第一位:秒 取值範圍(0-59)
第二位:分 取值範圍(0-59)
第三位:時 取值範圍(0-23)
第四位:天 取值範圍(0-31)
第五位:月 取值範圍(0-11)
第六位: 星期 取值範圍(1-7 1=SUN MON TUE WED THU FRI SAT)
第七位:年份 (1970-2099)
一個cron表達式可以有七位也可以有六位
每一位都有三種表達方式
第一種:10(直接寫一個值)假如是第一位(第一位代表秒),每分鐘的第10秒運行。
第二種:0/10表示每10秒鐘運行一次
第三種:0-10表示每分鐘的0-10秒,每秒運行一次