Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | About

2.21. Spring boot with Scheduling

項目中經常會用到計劃任務,spring Boot 中通過@EnableScheduling啟用計劃任務,再通過@Scheduled註解配置計劃任務如果運行。

2.21.1. Application.java

Application.java

啟用計劃任務, 在Spring Boot啟動類加上註解@EnableScheduling,表示該項目啟用計劃任務

			
package api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({ "api.config", "api.web", "api.rest", "api.service","api.schedule" })
@EnableMongoRepositories
@EnableJpaRepositories
@EnableScheduling
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}
				
			

開啟計劃任務 @EnableScheduling

確保你的計劃任務在 @ComponentScan 包中。

2.21.2. Component

在計劃任務方法上加上@Scheduled註解,表示該方法是一個計劃任務,項目啟動後會去掃瞄該註解的方法並加入計劃任務列表。

			
			
package api.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
public final static long ONE_DAY = 24 * 60 * 60 * 1000;
public final static long ONE_HOUR = 60 * 60 * 1000;

public ScheduledTasks() {
// TODO Auto-generated constructor stub
}

@Scheduled(fixedRate = 5000) //5秒運行一次調度任務
public void echoCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}

@Scheduled(fixedRate = ONE_DAY)
public void scheduledTask() {
System.out.println("每隔一天執行一次調度任務");
}

@Scheduled(fixedDelay = ONE_HOUR)
public void scheduleTask2() {
System.out.println("運行完後隔一小時就執行任務");
}

@Scheduled(initialDelay = 1000, fixedRate = 5000)
public void doSomething() {
// something that should execute periodically
}

@Scheduled(cron = "0 0/1 * * * ? ")
public void ScheduledTask3() {
System.out.println(" 每隔一分鐘執行一次任務");
}

}
			
			

@Scheduled參數說明

				@Scheduled註解有一些參數,用於配置計劃任務執行頻率,執行時段等。

				cron :cron表達式,e.g. {@code "0 * * * * ?"}從前到後依次表示秒 分 時 日 月 年
				zone:設置時區,指明計劃任務運行在哪個時區下,預設為空,採用操作系統預設時區
				fixedDelay:同一個計劃任務兩次執行間隔固定時間,單位毫秒,上次執行結束到下次開始執行的時間,以long類型複製
				fixedDelayString:同一個計劃任務兩次執行間隔固定時間,單位毫秒,上次執行結束到下次開始執行的時間,以String類型賦值
				fixedRate:以一個固定頻率執行,單位毫秒,表示每隔多久執行一次,以long類型賦值
				fixedRateString:以一個固定頻率執行,單位毫秒,表示每隔多久執行一次,以String類型賦值
				initialDelay:延遲啟動計劃任務,單位毫秒,表示執行第一次計劃任務前先延遲一段時間,以long類型賦值
				initialDelayString:延遲啟動計劃任務,單位毫秒,表示執行第一次計劃任務前先延遲一段時間,以String賦值
			

2.21.3. 查看日誌

				tail -f spring.log
			

2.21.4. 計劃任務控制

matchIfMissing = true, 如果改屬性條目不存在返回 true

				@ConditionalOnProperty("batch.metrics.export.influxdb.enabled")

				# mybean.enabled = true
				@ConditionalOnProperty(value='mybean.enabled')
				@ConditionalOnProperty(value = "endpoints.hal.enabled", matchIfMissing = true)

				# server.host = localhost
				@ConditionalOnProperty(name="server.host", havingValue="localhost")
				@ConditionalOnExpression("'${server.host}'=='localhost'")

				# spring.rabbitmq.dynamic = true
				@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
				@ConditionalOnProperty(prefix = "extension.security.cors", name = "enabled", matchIfMissing = false)
				@ConditionalOnProperty(prefix = "camunda.bpm.job-execution", name = "enabled", havingValue = "true", matchIfMissing = true)

				# spring.social.auto-connection-views = true
				@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
			

使用案例

			
package mis.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@ConditionalOnProperty("mis.schedule.enabled")
@Component
public class ScheduledTasks {
	private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
	public final static long ONE_DAY = 24 * 60 * 60 * 1000;
	public final static long ONE_HOUR = 60 * 60 * 1000;
	public final static long ONE_SECOND = 1000;

	public ScheduledTasks() {
		// TODO Auto-generated constructor stub
	}

	@Scheduled(fixedDelay = ONE_SECOND)
	public void scheduleTaskSplitLine() {
		logger.info("==================== {} ====================", dateFormat.format(new Date()));
	}
}
			
			

application.properties 配置如下

				mis.schedule.enabled=true