Spring定時任務 @Scheduled註解(多例項支援)
阿新 • • 發佈:2019-02-02
- 新增pom
- 資料庫指令碼
- 修改配置檔案
- 測試類
一. 新增pom
因為要使用多例項排程,所以我是用了分散式鎖shedlock,Spring pom請自行新增
<!-- shedlock --> <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-spring</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-provider-jdbc-template</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-provider-jdbc</artifactId> <version>1.0.0</version> </dependency>
二. 資料庫指令碼
建立shedlock表,shedlock用
CREATE TABLE shedlock(
name VARCHAR(64),
lock_until TIMESTAMP(3) NULL,
locked_at TIMESTAMP(3) NULL,
locked_by VARCHAR(255),
PRIMARY KEY (name)
)
三. 修改配置檔案
如圖,在xml中新增途中4行
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd xmlns:task="http://www.springframework.org/schema/task <task:annotation-driven/>
並新增如下配置(shedlock)
<!-- lock provider of your choice (jdbc/zookeeper/mongo/whatever) --> <bean id="lockProvider" class="net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider"> <constructor-arg ref="dataSource"/> </bean> <bean id="scheduler" class="net.javacrumbs.shedlock.spring.SpringLockableTaskSchedulerFactoryBean"> <constructor-arg> <task:scheduler id="sch" pool-size="10"/> </constructor-arg> <constructor-arg ref="lockProvider"/> <constructor-arg name="defaultLockAtMostFor"> <bean class="java.time.Duration" factory-method="ofMinutes"> <constructor-arg value="10"/> </bean> </constructor-arg> </bean>
四. 測試類
import net.javacrumbs.shedlock.core.SchedulerLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@EnableScheduling
public class ScheduleController {
private final static Logger logger = LoggerFactory.getLogger(ScheduleController.class);
private static final long FOURTEEN_MIN = 4 * 1000;
@Scheduled(cron = "0/5 * * * * ?")
@SchedulerLock(name = "eoaCall", lockAtLeastFor = FOURTEEN_MIN, lockAtMostFor = FOURTEEN_MIN)
public void schdule() {
logger.info("============== start ================"+new Date());
}
}